android在布局文件中自定义参数并在初始化时获取

在一些自定义view中我们往需要预先定义一些默认属性,这些参数常常跟view绑定的,因而在定义view的布局文件中添加这些属性就显得尤为有价值。整个过程分三步:

 

 1.定义declare-styleable,用于TypedArray来绑定对于的参数,在此需要在value目录里面新建文件:attrs.xml

 

 

Java代码   收藏代码
  1. <resources>  
  2.     <declare-styleable name="Def">  
  3.         <!-- The first screen the workspace should display. -->  
  4.         <attr name="num" format="integer"  />  
  5.          <attr name="length" format="integer"  />  
  6.     </declare-styleable>  
  7. </resources>  
 

   2.布局文件中配置控件,这里包含xml声明,还有对应的属性值

 

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     <span style="color: #ff0000;">xmlns:test="http://schemas.android.com/apk/res/com.yuhua.test"</span>  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <TextView  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/hello" />  
  12.     <span style="color: #ff0000;"> <com.yuhua.test.LocalView   
  13.          android:layout_width="fill_parent"  
  14.          android:layout_height="wrap_content"  
  15.          test:num ="3"  
  16.          test:length="5"  
  17.          /></span>  
  18. </LinearLayout>  
 

 

 3. 通过映射获取配置的属性

 

 

Java代码   收藏代码
  1. public class LocalView extends View {  
  2.   
  3.     private static final String TAG = "LocalView";  
  4.       
  5.     public LocalView(Context context) {  
  6.         super(context);  
  7.     }  
  8.   
  9.     public LocalView(Context context, AttributeSet attrs, int defStyle) {  
  10.         super(context, attrs, defStyle);  
  11.     }  
  12.   
  13.     public LocalView(Context context, AttributeSet attrs) {  
  14.         super(context, attrs);  
  15.         TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Def);  
  16.         Log.i(TAG, a.getInt(R.styleable.Def_length, 0) + "===" + a.getInt(R.styleable.Def_num, 0));  
  17.     }  
  18. }  
 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值