在res/values下创建attrs.xml

本文详细介绍了如何在Android中自定义组件并利用attrs.xml文件来定义组件属性,包括属性的创建、组件中使用属性以及在布局文件中应用自定义组件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

[html]   view plain copy
  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文件的定义

[java]   view plain copy
  1. public class MyRadioButton extends RadioButton {  
  2.     private String url;  
  3.       
  4.     public MyRadioButton(Context context, AttributeSet attrs) {  
  5.         super(context, attrs);  
  6.         TypedArray taArray = context.obtainStyledAttributes(attrs,R.styleable.MyRadioButton);  
  7.         this.url = taArray.getString(R.styleable.MyRadioButton_str);  
  8.         taArray.recycle();  
  9.     }  
  10.   
  11.     public String getUrl() {  
  12.         return url;  
  13.     }  
  14.   
  15.     public void setUrl(String url) {  
  16.         this.url = url;  
  17.     }  
  18.       
  19.   
  20. }  

a. TypedArray是存放资源R.styleable.MyRadioButton指定的属性集合。
b. 通过getXXX()获取属性值。
c. recycle()结束绑定

 

3.在布局文件中使用

[html]   view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.     <RadioGroup   
  7.        android:layout_width="fill_parent"  
  8.        android:layout_height="wrap_content"  
  9.        >  
  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.youkuaiyun.com"  
  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.youkuaiyun.com"  
  21.             />  
  22.          
  23.    </RadioGroup>  
  24.   
  25. </LinearLayout>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值