Saturday, September 26, 2020

Get system attributes in android custom View

We all know that in android development, the method of obtaining custom parameters of custom View is:


TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.Horiz);


We can get these custom parameters:


app:defaultValue="5"


app:valueFrom="2"


app:valueTo="10"


But sometimes we want to get the parameters of the system View itself, like this:


android:layout_width="200dp"


android:textSize="32sp"


android:columnCount="3"


In fact, the acquisition method is still like this:


TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.Hori);


Just refer to the "android:" namespace when defining attrs.


<?xml version="1.0"encoding="utf-8"?>


<resources>


<declare-styleable name="Horiz">


<attr name="android:textSize"/>


<attr name="android:textColor"/>


<attr name="android:defaultValue"/>


<attr name="android:valueFrom"/>


<attr name="android:valueTo"/>


<attr name="android:columnCount"/>


</declare-styleable>


</resources>


In this way, you can directly use the commonly used android naming when layout custom View.


<com.xiaoyifei.horizo


android:id="@+id/id_horizontal_picker"


android:layout_width="200dp"


android:background="#000000"


android:textSize="32sp"


android:textColor="@android:color/white"


android:defaultValue="5"android:valueFrom="2"


android:valueTo="10"


android:columnCount="3"


android:layout_height="50dp"/>

No comments:

Post a Comment