declare-styleable是给自定义控件添加自定义属性用的
1.首先,先写attrs.xml
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
04 | < declare-styleable name = "TestAttr" > |
05 | < attr name = "name" format = "reference" /> |
07 | < flag name = "child" value = "10" /> |
08 | < flag name = "young" value = "18" /> |
09 | < flag name = "oldman" value = "60" /> |
11 | < attr name = "textSize" format = "dimension" /> |
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 |
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" |
15 | attrstest:textSize = "@dimen/aa" |
16 | android:text = "@string/hello" /> |
xmlns:attrstest="http://schemas.android.com/apk/res/com.arlos.attrstest"
attrstest是随便写的.后面的包名是你所在的项目的根包.也就是在manifest里的com.arlos.attrstest
2.2 在自定义的控件里写属性 3. 最后在控件的构造方法里取得这些值
01 | public class MyTestView extends TextView { |
03 | public MyTestView(Context context, AttributeSet attrs) { |
04 | super (context, attrs); |
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); |