Android:将列表视图项设置为“已选中”(突出显示)

时间:2012-10-05 08:19:22

标签: android listview selector highlight

在我的应用程序中,我想要在平板电脑上执行类似于gmail应用程序的操作,在左侧有项目列表,在右边有一个包含该项目内容的片段,就像gmail app这个内容正在选择后下载。点击一个项目后,我希望它保持高亮显示,直到我改变选择。 我达到了这个有效的点,但只有当我在同一个项目上点击两次时,所以首先我点击,选择工作,然后项目返回到其“默认”状态,如果我再次点击它,选择器(选择)状态)是可见的。

这是我到目前为止所做的:

1)选择器(listitem_background.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/solid_white" android:state_pressed="false" android:state_selected="false"/>
    <item android:drawable="@drawable/listitem_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/listitem_focused" android:state_selected="true"/>

</selector>

2)对于列表项的顶部线性布局:

android:background="@drawable/listitem_background"

(我尝试将其设置为listselector)

3)这是ListView:

<ListView
    android:id="@+id/my_list_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:choiceMode="singleChoice"
    android:dividerHeight="1dp"
    android:drawSelectorOnTop="true"
    android:fadeScrollbars="true"
    android:fastScrollEnabled="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:scrollbarFadeDuration="100"
    android:scrollbars="vertical" />

4)在代码部分,我尝试使用它:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    view.setSelected(true);
    ...
}

[编辑]事实上,我注意到在屏幕右侧提交片段后,选择会丢失。如果我不提交片段,它就像一个魅力...... 我想我在选择器中需要这样的东西:

<item android:drawable="@drawable/listitem_focused" android:state_activated="true" android:state_focused="false"/>

但显然不是这个......

2 个答案:

答案 0 :(得分:45)

好的,终于得到了答案。

想法是在选择器和

中使用state_activated
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE) 
代码中的

android:choiceMode="singleChoice"
xml中的

,当然是

这就是选择器的样子:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/solid_white" android:state_activated="false"/>
    <item android:drawable="@drawable/solid_white" android:state_activated="false" android:state_pressed="false"/>
    <item android:drawable="@drawable/listitem_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/listitem_focused" android:state_activated="true"/>

</selector>

这是列表项布局的方式:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/listitem_background"
    android:orientation="vertical" >
...
<LinearLayout/>

答案 1 :(得分:4)

我遇到了同样的问题,然后我在项目视图xml中只需要一个简单的行。

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

This post可以提供帮助

相关问题