Android custom attributes

Here I customize a View to illustrate the usage of custom properties.

Part 1. Customize a View:


public class MyView extends View {
    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyView);
        Log.d("xyz","name:" + typedArray.getString(R.styleable.MyView_gylName) + "age:" + typedArray.getString(R.styleable.MyView_gylAge));
        //MyView_gylName and MyView_gylAge are custom attributes, don't worry
        typedArray.recycle();
    }
}


This View has no function. It obtains the values ​​of the two custom attributes and prints them out in the log.
Two points need to be paid attention to here:
1. public final TypedArrayStyledAttributes (AttributeSet obtain set, int[] attrs), here the second parameter R.styleable.MyView , the red part is the value of the name attribute of the declare-styleable tag in the custom attribute. 2.
You can use the AttributeSet object, that is, attrs, to get the value of the custom attribute, but it is more troublesome. It is recommended to use TypedArray.


Part 2 .Build attr.xml under values

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="gylName" format="string"/>
        <attr name="gylAge" format="integer"/>
    </declare-styleable>
</resources>


declare-styleable is optional, that is to say, you can write the attr tag directly in the resource tag, but it is recommended to write it in the declare-styleable...

Part 3. Layout page

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ray="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.learn.gyl.xutilssample.MyView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ray:gylAge="18"
        ray:gylName="gyl"/>
</LinearLayout>


Pay attention to the namespace: xmlns: ray = "http://schemas.android.com/apk/res-auto" The
red part is the part in the ray: gylAge = "18" custom control.


Running results:
xyz: name:gylage:18





Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326626656&siteId=291194637