Android之 自定义属性 的使用

1.自定义一个view文件MyView.java

2.定义自定义属性文件values/attrs.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <declare-styleable name="MyAtrr">
        <attr name="textcolor" format="color"/>
        <attr name="textsize" format="dimension"/>
    </declare-styleable>
</resources>

3.在主布局文件中使用自定义view和自定义属性

    xmlns:MySpace="http://schemas.android.com/apk/res/com.example.attrtest" //添加命名空间,红色的为包名

 <com.example.attrtest.MyView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        MySpace:textsize="25dp"
        MySpace:textcolor="#FF00FF00"   
        />

注意:给textcolor赋值时,是8位,不然在程序中会获取失败

4.在自定义view的初始化时获取自定义属性

自定义view在布局文件中初始化时,调用2个参数的构造函数

TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MyAtrr);
int textcolor=ta.getColor(R.styleable.MyAtrr_textcolor, Color.RED);   
float textsize=ta.getDimension(R.styleable.MyAtrr_textsize, 30);

两个获取函数的第二个参数都是在没有添加自定义属性时给定的默认值

就这么简单。

上源代码:http://download.csdn.net/detail/wulongtiantang/5134371

你可能感兴趣的:(自定义属性,Android中,的使用)