android - "?android:attr/activatedBackgroundIndicator"是如何工作的?

标签 android

我正在寻找如何在显示选择的上下文操作栏时突出显示列表中的选定项目,我找到的解决方案是设置我的行布局的 android:background 属性xml 到 "?android:attr/activatedBackgroundIndicator".

但是如何设置呢?

  1. 所涉及的机制是什么?
  2. “?”、“attr”、“activatedBackgroundIndicator”等语法元素是什么意思?
  3. “activatedBackgroundIndicator”的含义在哪里定义?

最佳答案

如果你有法医的心情,这里是如何挖掘并找出发生了什么。

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

直观地说,这意味着将背景设置为某个可绘制对象。

但是让我们进一步分解它,看看我们如何得到我们神秘的可绘制对象。

准确地说,它的意思是“将背景属性设置为属性“activatedBackgroundIndicator”在当前主题中所指的内容

如果你理解了“在当前主题中所指”的部分,那么你就基本了解了幕后的一切。

基本上,activatedBackgroundIndicator 不是实际的可绘制对象,而是对可绘制对象的引用。那么“activateBackgroundIndictor”属性实际定义在哪里呢?

它定义在你的sdk目录中一个文件名attrs.xml。例如:

path_to_android_sdk/platforms/android-17/data/res/values/attrs.xml

如果你打开那个文件,你会声明如下:

<attr name="activatedBackgroundIndicator" format="reference" />

attrs.xml 是您声明稍后将在 View xml 中使用的所有属性的位置。 请注意,我们是在声明属性及其类型,而不是在此处实际分配值

实际值在 themes.xml 中分配。该文件位于:

path_to_android_sdk/platforms/android-17/data/res/values/themes.xml

如果您打开该文件,您将看到多个定义,具体取决于您使用的主题。例如,以下分别是主题名称 Theme、Theme.Light、Theme.Holo、Theme.Holo.Light 的定义:

<item name="activatedBackgroundIndicator">@android:drawable/activated_background</item>
<item name="activatedBackgroundIndicator">@android:drawable/activated_background_light</item>
<item name="activatedBackgroundIndicator">@android:drawable/activated_background_holo_dark</item>
<item name="activatedBackgroundIndicator">@android:drawable/activated_background_holo_light</item>

现在我们有了神秘的drawable。如果你选择第一个,它在 drawable 文件夹中定义:

path_to_android_sdk/platforms/android-17/data/res/drawable/activated_background.xml

如果您打开该文件,您将看到可绘制对象的定义,这对于了解正在发生的事情很重要。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@android:drawable/list_selector_background_selected" />
    <item android:drawable="@color/transparent" />
</selector>

这里我们定义了一个有两种状态的drawable——默认状态是透明背景,如果状态是“state_activated”,那么我们的drawable就是“list_selector_background_selected”。

this link有关可绘制对象和状态的背景信息。

“list_selector_background_selected”是一个 9 补丁 png 文件,位于 drawable-hdpi 文件夹中。

现在您可以了解为什么我们将 activateBackgroundIndicator 定义为引用而不是直接链接到可绘制文件 - 它允许您根据主题选择正确的可绘制对象。

关于android - "?android:attr/activatedBackgroundIndicator"是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008150/

相关文章:

c# - 如何使用函数从sqlite数据库中获取数据?

android - 在ubuntu中设置android home

android - 在android ListView 中显示JSONArray的结果

Android-按下后退按钮时如何关闭进度对话框

android - 自动填充安卓收件箱

android - 生成签名包需要 gradle 版本 3.2.0 或更高

java - 我如何使用 Java 解析 Wikiquotes 响应?

android - 在 Activity 上调用 onPause 时数据会发生什么

android - 该项目不是基于 Gradle 的项目。如何从根目录打开项目?

android - 使用 ContactsContract 批量添加联系人