Android中使用attrs.xml文件定制RadioButton
掃描二維碼
隨時(shí)隨地手機(jī)看文章
Android中使用attrs.xml文件定制RadioButton
1.在res/values下創(chuàng)建attrs.xml
1 |
<declare-styleable name="MyRadioButton"> |
2 |
<attr name="str" format="string"/> |
3 |
</declare-styleable> |
MyRadioButton為組件名字,隨意起,attr標(biāo)簽定義組件的屬性,name對(duì)應(yīng)的是屬性名,format是屬性的類型,具體可參見《 [Android]attrs.xml文件中屬性類型format值的格式》。
2.在自定義的組件中使用attrs.xml文件的定義
01 |
public class MyRadioButton extends RadioButton { |
02 |
private String url; |
03 |
|
04 |
public MyRadioButton(Context context, AttributeSet attrs) { |
05 |
super(context, attrs); |
06 |
TypedArray taArray = context.obtainStyledAttributes(attrs,R.styleable.MyRadioButton); |
07 |
this.url = taArray.getString(R.styleable.MyRadioButton_str); |
08 |
taArray.recycle(); |
09 |
} |
10 |
|
11 |
public String getUrl() { |
12 |
return url; |
13 |
} |
14 |
|
15 |
public void setUrl(String url) { |
16 |
this.url = url; |
17 |
} |
18 |
|
19 |
} |
a. TypedArray是存放資源R.styleable.MyRadioButton指定的屬性集合。
b. 通過getXXX()獲取屬性值。
c. recycle()結(jié)束綁定 3.在布局文件中使用
01 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" |
02 |
xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815" |
03 |
android:layout_width="fill_parent" |
04 |
android:layout_height="fill_parent" |
05 |
android:orientation="vertical" > |
06 |
<RadioGroup |
07 |
android:layout_width="fill_parent" |
08 |
android:layout_height="wrap_content" |
09 |
> |
10 |
<net.csdn.blog.wxg630815.MyRadioButton |
11 |
android:layout_width="fill_parent" |
12 |
android:layout_height="wrap_content" |
13 |
android:id="@+id/myradio1" |
14 |
demo:str="1.csdn.net" |
15 |
/> |
16 |
<net.csdn.blog.wxg630815.MyRadioButton |
17 |
android:layout_width="fill_parent" |
18 |
android:layout_height="wrap_parent" |
19 |
android:id="@+id/myradio2" |
20 |
demo:str="2.csdn.net" |
21 |
/> |
22 |
|
23 |
</RadioGroup> |
24 |
|
25 |
</LinearLayout> |
注意: xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815"
只有聲明這句以后,url屬性才會(huì)被布局文件識(shí)別。net.csdn.blog.wxg630815指的是AndroidManifest.xml文件中manifest元素的package屬性值。
使用demo:str給url賦值。





