当前位置:首页 > 嵌入式 > 嵌入式软件
[导读] Android中使用attrs.xml文件定制RadioButton1.在res/values下创建attrs.xml 1 <declare-styleable name="MyRadioButton">

 Android中使用attrs.xml文件定制RadioButton

1.在res/values下创建attrs.xml

1 <declare-styleable name="MyRadioButton">
2         <attr name="str" format="string"/>
3 </declare-styleable>

MyRadioButton为组件名字,随意起,attr标签定义组件的属性,name对应的是属性名,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()结束绑定 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属性才会被布局文件识别。net.csdn.blog.wxg630815指的是AndroidManifest.xml文件中manifest元素的package属性值。

使用demo:str给url赋值。

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭