android中?attr/**与@drawable/**或@color/**等的区别及用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011153817/article/details/77937562

前言

今天在写一个Demo,研究主题的时候,遇到了【?attr/colorPrimary】这个用法,由于网上都是千篇一律的回答,所以我只能硬着头皮去看源码了,茶壶煮饺子,暂且记下来,作为备忘录吧。

一、?attr/**

这个Google把它叫做“预定义样式”,字面意思就是“预先定义好的样式”。也就是相当于给这个样式定义一个变量,随后是可以进行赋值的。

用的最多的场景就是自定义控件了,比如我现在需要自定义一个控件,要求它的字体颜色是可以动态修改的。此时,我们可以这样做:

  • 第一步:在attrs.xml中声明一个属性:
<declare-styleable name="SunnyAttr">

</declare-styleable>
  • 第二步:指定属性的名字及 属性值的类型
<declare-styleable name="SunnyAttr">
    <attr name="sunnyTextColor" format="reference"/>
    <attr name="sunnyTextColorWhite" format="color"/>
</declare-styleable>

属性值 的类型有以下几种:

  1. reference: 指参考指定Theme中的资源ID(比如:@string/test)
  2. color:指颜色值(比如:#FFFF0000)
  3. boolean: 布尔值(比如:true)
  4. dimension:尺寸(比如:100dp)
  5. float:浮点型(比如:0.3)
  6. integer:整型(比如:1)
  7. string:字符串
  8. fraction:百分数(比如:100%)
  9. flag:或运算(比如:0x10 | 0x11)
  10. enum:枚举

  • 第三步:由于从源码里面窥探出,attr/是跟随Theme来变化的,因此我们可以定义一个继承自Android系统某一主题的主题样式:
<style name="SunnyTheme" 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>

</style>
  • 第四步:在自定义主题里面,再定义一个供外面调用的属性名,并赋值:
<style name="SunnyTheme" 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="sunnyTextColorRed">@color/sunnyTextColorYellow</item>
</style>
  • 第五步:最后我们在xml中使用自定义控件的自定义属性时,就可以为它赋值了:
<com.smartbracelet.sunny.sunnydemo3.SunnyTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="设置界面"
    app:sunnyTextColor="?attr/sunnyTextColorRed"
    />

二、@color,@drawable

说完?attr/,再看@color与@drawable,后面2个是我们平时最常用的,就是指定资源,不是动态的,不会随着主题变化

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="红色"
    android:textColor="@color/sunnyTextColorRed"
    />

以上,就是?attr/与@color,@drawable的一个小总结。。。。

猜你喜欢

转载自blog.csdn.net/u011153817/article/details/77937562