加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

declare-styleable的使用

发布时间:2020-12-15 23:29:04 所属栏目:百科 来源:网络整理
导读:declare-styleable是给自定义控件添加自定义属性用的 1.首先,先写attrs.xml 01 ? xml version = "1.0" encoding "utf-8" ? 02 resources 03 04 declare-styleable name "TestAttr" 05 attr "name" format "reference" / 06 "age" 07 flag "child" value "10"

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. 最后在控件的构造方法里取得这些值
  
  
view source
print ?
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}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

相关内容
推荐文章
站长推荐
热点阅读