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

一、?attr/**

   这个google叫预定义样式

   这个是用在多主题时的场景,属性值会随着主题而改变。

但并不是一上来就可以用的,必须做足以下准备工作:

1,如果是自定义控件,请在style.xml中或attrs.xml中声明属性:

<declare-styleable name="SunnyAttr">
    <attr name="sunnyTextColor" format="reference"/>
    <attr name="sunnyBgColor" format="reference"/>
    <attr name="sunnyTextColorWhite" format="color"/>
    <attr name="sunnyTextColorRed" format="reference"/>
    <attr name="textColor" format="reference"></attr>
</declare-styleable>

如红色字体所示,必须指明format为reference


2,因为attr/是跟随Theme来变化的,所以对attr跟随的属性必须在Theme里面声明:

<!-- Base application theme. -->
<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="sunnyTextColorRed">@color/sunnyTextColorYellow</item>
</style>

3,在对应的属性color,drawable等里面加入相应的资源

<color name="sunnyTextColorRed">#FFFF0000</color>

4,这样我就可以在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等

  这个就是我们平时最常用的,就是指定资源,不是动态的,不会随着主题变化

  

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

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

补充:

1.使用系统参数比如colorPrimaryDark时除了以上方式,也可以这样写:?android:attr/colorPrimaryDark ,不过只是支持android21以及以上

2.使用自定义参数(包括系统的动态参数)在selector中引用时,android21以及以下会报以下错误:

<item> tag requires a 'drawable' attribute or child tag defining a drawable

是个坑啊!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值