Android自定义View的自定义属性

使用案列

layout.xml
<com.example.rx_demo.MyView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:flag="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="flag" format="boolean" />
    </declare-styleable>
</resources>

自定义View取值
val typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyView)
val flag = typedArray.getBoolean(R.styleable.MyView_flag,true)
typedArray.recycle()

attrs是实现了一个xml解析器,可以通过它获取

<com.example.rx_demo.MyView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:flag="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

里面所有值

看看R.txt文件,关于自定义view属性的东西

int[] styleable MyView { 0x7f030378 }
int styleable MyView_flag 0
int attr flag 0x7f030378

实际上等价于
int[] styleable MyView { flag }
int styleable MyView_flag 0

由此可知R.styleable.MyView是一个数组,里面有一个flag的属性
我们可以通过这个数组过滤出我们想要的属性值,丢进数组
而R.styleable.MyView_flag是一个下标值,可以通过下标值拿到属性

posted @ 2021-07-02 10:08  c-若曦  阅读(154)  评论(0)    收藏  举报