android属性的使用以及obtainStyledAttributes的四种用法

attr

属性即变量,一个用于制作ui时需要的变量。既然是变量,就有变量的声明,赋值和使用:

声明

一般在values目录下的attrs.xml文件里使用attrs标签声明

//name:变量名称, format:变量类型
<attr name="attr1" format="string"/>    

动态获取的(通过obtainStyledAttributes方法),需要使用属性集包裹:

<declare-styleable name="AttrTextView1">
        <attr name="textColor" format="color"></attr>
        <attr name="text1" format="string"></attr>
        <attr name="textSize" format="dimension"></attr>
    </declare-styleable>

赋值

一般在values目录下的styles.xml文件里使用item标签声明

<style name="AttrStyle1" >
        <item name="textColor">@color/yellow</item>
        <item name="textSize">10dp</item>
        <item name="text1">第二种</item>
    </style>

外部必须使用style包裹,每一个style可以理解为一堆属性赋值的集合。可以为主题和样式使用。

使用

  • 静态使用:
    1. 通过style使用
<TextView
        style="@style/AttrStyleStatic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

//AttrStyleStatic的定义:
<style name="AttrStyleStatic" >
        <item name="android:textColor">@color/yellow</item>
        <item name="android:textSize">10dp</item>
        <item name="android:text">第四种</item>
    </style>
2. 预定义:
<TextView
        style="?attr/attr4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
//attr4对应当前主题里声明的item
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="attr4">@style/AttrStyle4</item>
    </style>
  • 动态使用:
    1. 在布局xml的根节点声明:
xmlns:app="http://schemas.android.com/apk/res-auto"
  1. 在需要的view上通过app:{属性名}引用:
<skin.example.com.attrslearn.view.AttrTextView1
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:text1="attr1"
        app:textColor="@color/colorPrimaryDark"
        app:textSize="10dp"/>
  1. 动态获取:
//对应于当前主题的赋值
context.getTheme().obtainStyledAttributes(R.styleable.AttrTextView1);
//对应指定的R.style.AttrStyle1样式下的赋值
context.getTheme().obtainStyledAttributes(R.style.AttrStyle1,R.styleable.AttrTextView1);
//对应自定义view的赋值,如上2
context.getResources().obtainAttributes(attrs, R.styleable.AttrTextView1);
//四个参数包括了上面的三种情况:
//第一个参数:对应自定义view的赋值
//第二个参数:属性集
//第三个参数:对应主题里的属性赋值,这里的属性一般不对应一个值而是一个样式的引用
//第四个参数:对应指定样式下的赋值
context.getTheme().obtainStyledAttributes(null, R.styleable.AttrTextView1,R.attr.attr4,0);

最后附上源码地址

猜你喜欢

转载自blog.csdn.net/weixin_38801333/article/details/79321729
今日推荐