Android自定义属性

这里我自定义一个View来说明自定义属性的用法.

Part 1.自定义一个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和MyView_gylAge是自定义属性,看官莫急
        typedArray.recycle();
    }
}


这个View什么功能都没,取得自定义的两个属性的值并在日志打印出来.
在这里需要注意两点:
1.public final TypedArray obtainStyledAttributes (AttributeSet set, int[] attrs),这里第二个参数R.styleable.MyView,红字部分是自定义属性中declare-styleable标签的name属性的值.
2.可以用AttributeSet对象也就是attrs来取自定义属性的值,但是比较麻烦,推荐用TypedArray.


Part 2.在values下建attr.xml

<?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是可以不要的,就是说可以直接在resource标签内写attr标签,但是,还是推荐写在declare-styleable里...

Part 3.布局页

<?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>


注意命名空间:xmlns:ray="http://schemas.android.com/apk/res-auto"
红字部分就是ray:gylAge="18"自定义控件里的部分.


运行结果:
xyz: name:gylage:18





猜你喜欢

转载自gonyulian415.iteye.com/blog/2315560