declare-styleable的使用

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

1.首先,先写attrs.xml

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

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

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

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念