Three steps to realize the custom properties of Android custom controls, and the weird error Unresolved reference: styleable

I have developed a custom Android UI control, which inherits from View, and then want to freely configure attributes like native controls in the layout XML, how to do it? In three steps:

Step 1: Create attrs.xml in the res/values ​​directory, and then declare custom attributes

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

In the above example, the name of the declare-styleable node is the name of the control, and the sub-nodes below are custom attributes, which can be declared in multiples and added one by one. Here we define a property called pcv_curve_color whose type is a color value.

Step 2: Read the custom property value in the constructor of the custom control class

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() // 别忘了这一句

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

Step 3: Configure custom attributes in layout 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"/>

You're done! But the problem also came: compilation error: Unresolved reference: styleable. What's going on here? Referring to other examples on GitHub, I found nothing wrong with it! Puzzled...

Don't give a damn! Pay attention to the warning message: Don't include `android.R` here; use a fully qualified name for each usage instead , that's the problem! When you encounter an unresolvable symbol in the process of writing code, pressing Alt + Enter is too smooth-when there are multiple sources of resolution, you will accidentally make a mistake. Back to our example, this R should be parsed as {your package name}.R instead of android.R , quickly delete import android.R at the head of the source file, and then press again at the constructor compilation error Alt + Enter, Euler~

Guess you like

Origin blog.csdn.net/happydeer/article/details/126687317