Android自定义属性

自定义属性

  1. 在res/values目录下增长属性定义文件attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyAttrs">
        <attr name="attrName" format="string" />
    </declare-styleable>
</resources>

经过<declare-styleable>标签声明了自定义属性,经过name属性来肯定引用的名称。<attr>标签订义哪些属性:name属性名称,format属性类型,有:string , integer , dimension , reference , color, enum。须要注意的地方是,有些属性能够指定多个类型,好比有些能够是颜色属性,也能够是引用属性,这种状况能够使用“|”来分隔不一样的属性:"color|reference"。android


  1. 在自定义控件中使用定义的属性
public class MyTextView extends TextView {

    private static String TAG = "MyTextView";

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        //将attrs.xml定义的declare-sytleable的全部属性的值存储在TypedArray中
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyAttrs);
        //从TypedArray中取出对应的值
        String customAttrValue = ta.getString(R.styleable.MyAttrs_customeAttrName);
        //获取完TypedArray的值后,必定要调用recycle方法回收资源
        ta.recycle();
        Log.d(TAG, "customAttrValue is " + customAttrValue);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

经过context.obtainStyleAttributes()方法获取在XML布局文件中定义的那些属性。接下来,就能够经过TyepedArray的getXXX()方法获取那些定义的属性值。这里须要注意的是,当获取完全部属性值后,不要忘了调用recyle()方法来完成资源的回收app


  1. 在布局文件中使用自定义属性
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.wh.myapplication.MainActivity">

    <com.example.wh.myapplication.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        custom:customeAttrName="Hello, Custom Attribute!"/>
</RelativeLayout>

xmlns:custom="http://schemas.android.com/apk/res-auto"指定引用的名字空间,这里将引用的第三方控件的名字空间取名为custom,以后在XML文件中使用自定义的属性时,就能够经过这个名字空间来引用:custom:customeAttrName="Hello, Custom Attribute!"。布局

相关文章
相关标签/搜索