declare-styleable是给自定义控件添加自定义属性用的
@H_301_5@1.首先,先写attrs.xml
01 |
<? xml version = "1.0" encoding "utf-8" ?> |
02 | <resources > |
03 |
04
attr
@H_301_5@
declare-styleable
name
"TestAttr"
05
"name"
format
"reference"
/>
06
"age"
flag
"young"
@H_301_5@
@H_301_5@
@H_301_5@
@H_301_5@
07
"child"
value
"10"
08
"18"
/>
09 | "oldman""60" 10 |
</attr 11 |
"textSize""dimension" 12 |
declare-styleable13 |
> |
reference指的是是从string.xml引用过来
@H_301_5@
flag是自己定义的,类似于android:gravity="top"
dimension 指的是是从dimension.xml里引用过来的内容.注意,这里如果是dp那就会做像素转换 2.在布局文件里的写法
@H_301_5@
@H_301_5@
@H_301_5@
@H_301_5@@H_301_5@ @H_301_5@ @H_301_5@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@H_301_5@xmlns:attrstest="http://schemas.android.com/apk/res/com.arlos.attrstest"attrstest是随便写的.后面的包名是你所在的项目的根包.也就是在manifest里的com.arlos.attrstest 2.2 在自定义的控件里写属性 3. 最后在控件的构造方法里取得这些值view source@H_301_5@ print ? @H_301_5@ @H_301_5@@H_301_5@
@H_301_5@@H_301_5@ @H_301_5@ @H_301_5@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} @H_301_5@猜你在找的XML相关文章