?attr/selectableItemBackground的使用(TypedArray,TypedValue)

在XML中引用: ?attr/

参考文章:Android xml资源文件中@、@android:type、@*、?、@+含义和区别
?attr/代表引用当前主题中的属性的值,?android:attr/代表引用系统的

android:background="?android:attr/selectableItemBackground"

定义和赋值

  • 定义
    那么selectableItemBackground是在哪里定义的呢?又是在哪里赋值的呢?
    在xml中点击?attr/可以进入到定义的页面,例如selectableItemBackground定义在:
    sdk\platforms\android-xx\data\res\values\attrs.xml 这个和所用的主题有关
<!-- Background drawable for bordered standalone items that need focus/pressed states. -->
<attr name="selectableItemBackground" format="reference" />
  • 赋值
    既然引用的是主题的属性,那应该就是在主题里面赋值了,一步步点击进使用的主题,最终在:
    sdk\platforms\android-xx\data\res\values\themes.xml
<item name="selectableItemBackground">@drawable/item_background</item>
<item name="selectableItemBackgroundBorderless">?attr/selectableItemBackground</item>

在代码中使用

像string/color/drawable这些资源,在代码中可以通过Resource的方法直接获取

Context.getResource().getString(R.string.id)

但?attr/用在多主题时的场景,属性值会随着主题而改变, 不能直接获取,这个google叫预定义样式
参考文章:Android,如何在代码中获取attr属性的值
在代码中获取selectableItemBackground

TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
int[] attribute = new int[] { android.R.attr.selectableItemBackground};
TypedArray typedArray = context.getTheme().obtainStyledAttributes(typedValue.resourceId, attribute);
Drawble drawable = typedArray.getDrawable(0);
typedArray.recycle();

自定义attr属性

参考文章:android中?attr/与@drawable/或@color/**等的区别

最后注意区分和自定义View时使用自定义属性的区别,请点击参考

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值