三步实现Android自定义控件的自定义属性,以及诡异错误 Unresolved reference: styleable

开发了一个自定义Android UI控件,继承自View,然后想要在布局XML里像原生控件一样随意配置属性,怎么做呢?分三步:

第一步:在res/values目录下创建attrs.xml,然后声明自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PointCaptureView">
        <attr name="pcv_curve_color" format="color|reference"/>
    </declare-styleable>
</resources>

上面示例中,declare-styleable节点的name即为控件名字,下面的子节点就是自定义属性,可以声明多个,依次添加即可。这里我们定义了一个名为pcv_curve_color的属性,其类型为一个颜色值。

第二步:在自定义控件类的构造函数中读取自定义属性值

class PointCaptureView : View {

constructor(context: Context, attr: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attr, defStyleAttr) {
        val a = context.obtainStyledAttributes(attr, R.styleable.PointCaptureView, defStyleAttr, 0)
        canvasPaintColor = a.getColor(R.styleable.PointCaptureView_pcv_curve_color, Color.YELLOW)
        a.recycle() // 别忘了这一句

        // 其他初始化代码
        // ...
}
}

第三步:在布局XML中配置自定义属性

<com.example.testbedandroid.widgets.PointCaptureView
        android:id="@+id/hapticView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        app:pcv_curve_color="@color/green"/>

大功告成!但问题也来了:编译出错:Unresolved reference: styleable。这是怎么回事呢?参考了GitHub上的其他示例,没发现有啥毛病呀!百思不得其解……

不卖关子了!注意那条警告信息:Don't include `android.R` here; use a fully qualified name for each usage instead,问题就在这儿啦!写代码过程中碰到无法解析的符号时,按Alt + Enter太顺了——当有多个解析来源时,一不小心就会搞错。回到我们的例子中,这个R应该解析为 {你的包名}.R 而不是 android.R ,赶紧在源文件头部把import android.R删了,然后在构造函数编译错误处重新按下Alt + Enter,欧拉~

猜你喜欢

转载自blog.csdn.net/happydeer/article/details/126687317
今日推荐