• 诡异错误 Unresolved reference: styleable


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

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

    1. "1.0" encoding="utf-8"?>
    2. <resources>
    3. <declare-styleable name="PointCaptureView">
    4. <attr name="pcv_curve_color" format="color|reference"/>
    5. declare-styleable>
    6. resources>

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

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

    1. class PointCaptureView : View {
    2. constructor(context: Context, attr: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attr, defStyleAttr) {
    3. val a = context.obtainStyledAttributes(attr, R.styleable.PointCaptureView, defStyleAttr, 0)
    4. canvasPaintColor = a.getColor(R.styleable.PointCaptureView_pcv_curve_color, Color.YELLOW)
    5. a.recycle() // 别忘了这一句
    6. // 其他初始化代码
    7. // ...
    8. }
    9. }

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

    1. <com.example.testbedandroid.widgets.PointCaptureView
    2. android:id="@+id/hapticView"
    3. android:layout_width="match_parent"
    4. android:layout_height="120dp"
    5. 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,欧拉~

  • 相关阅读:
    微信小程序实现底部操作栏
    vue3+vite使用viewerjs实现图片预览
    企业网络“卫生”实用指南
    Linux 防火墙 firewalld 常用命令
    矩阵乘法的性质
    【DFIR】蘇小沐的微信公众号
    【目标检测算法】YOLO-V5实战检测VOC2007数据集
    力扣-345.反转字符串中的元音字母
    应用于伺服电机控制、 编码器仿真、 电动助力转向、发电机、 汽车运动检测与控制的旋变数字转换器MS5905P
    The_Maya_Society
  • 原文地址:https://blog.csdn.net/happydeer/article/details/126687317