我有一个 ListView,它在手机上效果很好。现在我正在制作一个平板电脑 UI,左侧是 ListView,右侧是详细信息。
当我触摸一个项目时,只要按下它就会闪烁蓝色。我想保持这种蓝色,直到选择另一个项目,就像 Nexus 7 上的 Gmail 应用程序一样。
实现这一目标的最干净的方法是什么?我宁愿避免手动设置背景,我认为有一种方法可以将元素标记为“活动”元素并相应地为其设置主题。
实现这一目标的最干净的方法是什么?
您正在寻找的内容称为“激活”状态。为了使这项工作:
第 1 步:在res/values-v11/
中,有一个实现activated
. 例如,对于在AppTheme
此处定义声明的新项目,请使用以下内容:
<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light"></style>
<style name="activated" parent="AppTheme">
<item name="android:background">?android:attr/activatedBackgroundIndicator</item>
</style>
</resources>
步骤#2:res/values/
为任何旧设备定义相同的样式,就像存根样式资源一样,因此对它的引用继续有效:
<resources>
<style name="AppTheme" parent="android:Theme.Light"/>
<style name="activated" parent="AppTheme"/>
</resources>
步骤#3:在您的布局 XML 资源中的行中ListView
,添加style="@style/activated"
到根元素的属性列表中
步骤#4:将 设置为ListView
单选列表,例如 a 中的以下行ListFragment
:
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
您可以在此示例项目、此示例项目和此示例项目中看到这一点。有关前两个示例的更多背景信息,请参阅这个 SO 问题:Gmail 三片段动画场景的完整工作示例?
使用
android.R.layout.simple_list_item_activated_1
代替
R.layout.simple_list_item_checkable_1
.
只是为了有一天有人检查。
经过几天的搜索和拉扯我的头发后,我发现它activatedBackgroundIndicator
也可以在 ActionBarSherlock 造型系统中使用。大多数开发向后兼容应用程序的开发人员都使用 ActionBarSherlock,因此在大多数情况下使用 ActionBarSherlock 是一个不错的选择。因此,不要使用android:background="?android:attr/activatedBackgroundIndicator"
which 会在 11 之前的 android 版本中出现错误,只需使用:android:background="?activatedBackgroundIndicator"
这是示例行布局 xml 代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
//note the activatedBackgroundIndicator
android:background="?activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingBottom="2dip"
android:paddingTop="2dip" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:textSize="15sp" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingRight="5dip"
android:textSize="20dip" />
</LinearLayout>