• 诡异错误 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,欧拉~

  • 相关阅读:
    在线地图获取城市路网数据
    ES6中数组新增的方法-超级好用
    HTTP协议
    MAX/MSP SDK学习04:Messages selector的使用
    全栈性能测试教程之性能测试相关知识(二) Jmeter的应用
    【问卷分析】调节效应检验的操作①
    JavaScript——函数
    UML 2.0包括14种图
    Python刘诗诗
    SpringBoot请求响应
  • 原文地址:https://blog.csdn.net/happydeer/article/details/126687317