Android中 @和?区别以及?attr/**与@style/**等的区别

@和?的区别

 style="?android:attr/progressBarStyleHorizontal"
 style="@android:style/Widget.ProgressBar.Horizontal"
 
 
  • 1
  • 2

在设置style的时候既可以使用@也可以使用?,他们有什么区别呢??

  • 使用@表示使用固定的style,而不会跟随Theme改变,这style可以在对应的style.xml中找到。
  • 使用?表示从Theme中查找引用的资源名,这个google叫预定义样式,用在多主题时的场景,属性值会随着主题而改变。(?需要和attr配合使用)

例如上面的progressBarStyleHorizontal,查看\platforms\android-23\data\res\values\themes.xml文件,可以看到在不同的theme中,progressBarStyleHorizontal引用的style是不同的。看下面的示例:

在Theme中

<item name="progressBarStyleHorizontal">@style/Widget.ProgressBar.Horizontal</item>
 
 
  • 1

Theme.Holo中为

 <item name="progressBarStyleHorizontal">@style/Widget.Holo.ProgressBar.Horizontal</item>
 
 
  • 1

style和attr使用区别

style

<!--使用自定义的style-->
@style/Widget.AppCompat.ProgressBar.Horizontal
<!--使用系统自带的style-->
@android:style/Widget.ProgressBar.Horizontal
 
 
  • 1
  • 2
  • 3
  • 4

attr

<!--使用自定义的  ,下面两种方式等效-->
"?attr/属性"
"?属性"
<!--使用系统自带的 ,下面两种方式等效-->
"?android:属性"
"?android:attr/属性"

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

另外:

当引用系统自带的style和attr时

"@android:style/主题""@style/android:主题"等同

"?android:attr/属性""?attr/android:属性"等同
 
 
  • 1
  • 2
  • 3

自定义随主题改变的属性

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>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

如代码第五行所示,必须指明format为reference。这样自定义控件的属性就可以在xml使用,如果不明白,查看这里

2、 在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/sunnyTextColorRed</item>
</style>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

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

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"
    />
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值