使用attrs.xml自定义属性

来源:互联网 发布:阿里云域名空间备案 编辑:程序博客网 时间:2024/06/05 22:29

控件有很多属性,如android:id、android:layout_width、android:layout_height等,但是这些属性都是系统自带的属性。使用attrs.xml文件,可以自己定义属性。本文在Android自定义控件的基础上,用attrs.xml文件自己定义了属性。

首先,在values文件夹下,新建一个attrs.xml文件,文件内容如下:

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="CustomView">    <attr name="tColor" format="color" />    <attr name="tSize" format="dimension" />    </declare-styleable>    </resources>

其中,<declare-styleable name="CustomView">表明样式名称为CustomView,下面包含了两个自定义属性tColor和tSize,其中tColor是颜色(color)类的属性,tSize是尺寸(dimension)类的属性。

主窗体的布局文件如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"    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=".MainActivity" >        <com.hzhi.customview.CustomView        android:id="@+id/cusView"android:layout_width="wrap_content"android:layout_height="wrap_content"test:tColor="#00FFFF"test:tSize="30dp"    >    </com.hzhi.customview.CustomView></RelativeLayout>

定义了xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"(其中com.hzhi.customview是包名),在控件属性中就可以增加test:tColor和test:tSize两个属性。

CustomView.java的构造函数:

// 构造函数public CustomView(Context context, AttributeSet attrs) {super(context, attrs);// 获得TypedArrayTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);// 获得attrs.xml里面的属性值,格式为:名称_属性名,后面是默认值int tColor = a.getColor(R.styleable.CustomView_tColor, Color.GREEN); float tSize = a.getDimension(R.styleable.CustomView_tSize, 35);p.setColor(tColor);p.setTextSize(tSize);// 返回一个绑定资源结束的信号给资源a.recycle();}

首先从R.styleable.CustomView获得了TypedArray变量,再用getColor(),getDimension()等方法获取相应的属性值,属性格式为“样式名_属性名”,属性后面的参数是默认值。获得属性值以后,就可以应用这些属性值。recycle()方法用于返回信号给资源(不懂什么意思)。

运行结果如下:

 

感谢原作者:http://www.cnblogs.com/mstk/p/3575086.html

0 0