1.在res/values下建立attrs.xml
<declare-styleable name="MyRadioButton">
<attr name="str" format="string"/>
</declare-styleable>
MyRadioButton為組件名字,隨意起,attr標籤定義組件的屬性,name對應的是屬性名稱,format是屬性的類型,具體可參見《[Android]attrs.xml檔案中屬性類型format值的格式》。
2.在自訂的組件中使用attrs.xml檔案的定義
public class MyRadioButton extends RadioButton {
private String url;
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray taArray = context.obtainStyledAttributes(attrs,R.styleable.MyRadioButton);
this.url = taArray.getString(R.styleable.MyRadioButton_str);
taArray.recycle();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
a. TypedArray是存放資源R.styleable.MyRadioButton指定的屬性集合。
b. 通過getXXX()擷取屬性值。
c. recycle()結束綁定
3.在布局檔案中使用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<net.csdn.blog.wxg630815.MyRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/myradio1"
demo:str="1.csdn.net"
/>
<net.csdn.blog.wxg630815.MyRadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_parent"
android:id="@+id/myradio2"
demo:str="2.csdn.net"
/>
</RadioGroup>
</LinearLayout>
注意:xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815"
只有聲明這句以後,url屬性才會被布局檔案識別。net.csdn.blog.wxg630815指的是AndroidManifest.xml檔案中manifest元素的package屬性值。
使用demo:str給url賦值。
摘自 行在路上