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

来源:互联网 发布:vim c语言语法高亮 编辑:程序博客网 时间:2024/05/29 11:24

在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时使用自定义属性的区别,请点击参考

阅读全文
0 0
原创粉丝点击