android Theme使用二

来源:互联网 发布:切片软件 编辑:程序博客网 时间:2024/06/06 00:07

以前我们布局的时候使用一个属性都是android:开头。这是表示我们使用的是android自带的属性,那我们在attrs.xml中定义的数据怎么引用呢?

1.2.2使用自定义的属性

1)、在res/values文件下定义一个attrs.xml文件,代码如下:

<?xml version="1.0"encoding="utf-8"?>

<resources>

   <declare-styleable name="ToolBar">

       <attr name="buttonNum" format="integer"/>

       <attr name="itemBackground"format="reference|color"/>

</declare-styleable>

<attrname="buttonindex" format=" reference "/>

</resources>

 

2)、在布局xml中如下使用该属性:

<?xml version="1.0"encoding="utf-8"?>

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   xmlns:toolbar="http://schemas.android.com/apk/res-auto"

   android:layout_width="fill_parent"

   android:layout_height="fill_parent" >

<cn.zzm.toolbar.ToolBar

              android:id="@+id/gridview_toolbar"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       toolbar:buttonNum="5"

       toolbar:itemBackground="@drawable/control_bar_item_bg"/>

</RelativeLayout>

注意:xmlns:toolbar=”http://schemas.android.com/apk/res-auto”表示自定义的名字空间,等号后面是固定的,在以前的android版本中自定义名字空间不是这样的。现在统一了。

 

 

3)、在自定义组件中,可以如下获得xml中定义的值:

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);

buttonNum =a.getInt(R.styleable.ToolBar_buttonNum, 5);

itemBg =a.getResourceId(R.styleable.ToolBar_itemBackground, -1);

a.recycle();

 

注意:代码里面获取一个属性的值规则。R.styleable.+ <declare-styleable name="ToolBar">+下划线+属性名称(<attrname="buttonNum">

如上面的a.getInt(R.styleable.ToolBar_buttonNum,5);

 

TypedArray 有很多getxxx方法,可以帮我们获取值:



代码里面使用属性是很常见的,特别是在看android源码的时候,android中的view及其子类都使用了这种方式。这有什么好处呢?这种方式更灵活,可以让我们动态的改变view的显示方式,比如字体大小,字体颜色,背景图片。无需改变代码只需要改变资源文件就可以达到各种效果。


0 0
原创粉丝点击