declare-styleable的使用

原文地址:

http://my.oschina.net/u/555002/blog/85076


declare-styleable是给自定义控件添加自定义属性用的

1.首先,先写attrs.xml

01 <?xml version="1.0" encoding="utf-8"?>
02 <resources>
03  
04     <declare-styleable name="TestAttr">
05         <attr name="name" format="reference" />
06         <attr name="age">
07             <flag name="child" value="10" />
08             <flag name="young" value="18" />
09             <flag name="oldman" value="60" />
10         </attr>
11         <attr name="textSize" format="dimension" />  
12     </declare-styleable>
13 </resources>

reference指的是是从string.xml引用过来
flag是自己定义的,类似于 android:gravity="top"
dimension 指的是是从dimension.xml里引用过来的内容.注意,这里如果是dp那就会做像素转换 2.在布局文件里的写法
 
 
01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03    xmlns:attrstest="http://schemas.android.com/apk/res/com.arlos.attrstest"
04    android:layout_width="fill_parent"
05    android:layout_height="fill_parent"
06    android:orientation="vertical" >s
07 
08    <com.arlos.attrstest.MyTestView
09        android:id="@+id/tvTest"
10        android:layout_width="fill_parent"
11        android:layout_height="wrap_content"
12         attrstest:name="@string/myname"
13         android:gravity="top"
14         attrstest:age="young"
15         attrstest:textSize="@dimen/aa"
16        android:text="@string/hello" />
17 
18</LinearLayout>
    2.1 先引用这个dtd
xmlns:attrstest="http://schemas.android.com/apk/res/com.arlos.attrstest"
attrstest是随便写的.后面的包名是你所在的项目的根包.也就是在manifest里的com.arlos.attrstest

 2.2 在自定义的控件里写属性 3. 最后在控件的构造方法里取得这些值
 
 
01public class MyTestView extends TextView {
02 
03    public MyTestView(Context context, AttributeSet attrs) {
04        super(context, attrs);
05 
06        TypedArray tArray = context.obtainStyledAttributes(attrs,
07                R.styleable.TestAttr);
08        String name = tArray.getString(R.styleable.TestAttr_name);
09        System.out.println("name = " + name);
10        int age = tArray.getInt(R.styleable.TestAttr_age, 200);
11        System.out.println("age = " + age);
12         float demin = tArray.getDimension(R.styleable.TestAttr_textSize,0);
13         System.out.println("demin = " + demin);
14        tArray.recycle();
15    }
16}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值