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