Android:在ListView选择后保持蓝色背景

时间:2012-09-12 10:39:37

标签: android listview tablet

我有一个ListView,它在手机上运行良好。现在我正在创建一个平板电脑用户界面,左侧是ListView,右侧是详细信息。

当我触摸某个项目时,只要按下它就会闪烁蓝色。我希望保持蓝色,直到选择了另一个项目,就像Nexus 7上的Gmail应用程序一样。

实现这一目标的最简洁方法是什么?我宁愿避免手动设置背景,我认为有一种方法可以将元素标记为“活动”元素并相应地对其进行主题化。

3 个答案:

答案 0 :(得分:18)

  

实现这一目标的最简洁方法是什么?

您正在寻找的是“激活”状态。要做到这一点:

步骤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:在ListView中行的布局XML资源中,将style="@style/activated"添加到根元素的属性列表中

步骤4:将ListView设置为单选项列表,例如ListFragment中的以下行:

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

您可以在this sample projectthis sample projectthis sample project中查看此操作。有关前两个样本的更多背景信息,请参阅此SO问题:Complete Working Sample of the Gmail Three-Fragment Animation Scenario?

答案 1 :(得分:4)

使用

android.R.layout.simple_list_item_activated_1

而不是

R.layout.simple_list_item_checkable_1

只是有一天有人检查。

答案 2 :(得分:2)

经过几天的搜索和拉扯我的头发后,我发现ActionBarSherlock样式系统中也可以使用activatedBackgroundIndicator。开发向后兼容应用程序的大多数开发人员使用ActionBarSherlock,因此在大多数情况下使用ActionBarSherlock是一个不错的选择。因此,不要使用会在11之前的Android版本中出错的android:background="?android:attr/activatedBackgroundIndicator",而是使用: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>