ListFragment选定项目

Ara*_* GM 3 android

我在ListFragment上有一个ListView,它使用SimpleCursorAdapter来生成我的列表.我想在我的ListView中突出显示所选项目,我尝试过:

v.setBackgroundResource(R.color.listselect_light_blue);
Run Code Online (Sandbox Code Playgroud)

在onListItemClick但它工作奇怪,它选择两行当我点击其中一个项目,我希望它是单一,我也设置选择模式

<ListView android:id="@id/android:list"
           android:layout_width="fill_parent"
           android:layout_height="fill_parent" 
           android:choiceMode="singleChoice"   
           android:cacheColorHint="#00000000"
            />
Run Code Online (Sandbox Code Playgroud)

我已经尝试了ListSelector但是当我点击一个项目时它不会突出显示,直到我滚动列表并突然显示.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getListView().setSelector(R.drawable.listview_selector);

}
Run Code Online (Sandbox Code Playgroud)

并且:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:drawable="@color/listselect_light_blue" />
</selector>
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

Dix*_*tel 5

如果要突出显示所选项目,请尝试这种方式Listview.

这适合我.

首先在使用setSelector(..)之前在Listfragment中设置Adapter.

 setListAdapter(mAdapter);
 getListView().setSelector(R.drawable.fragment_listselector);      
Run Code Online (Sandbox Code Playgroud)

fragment_listselector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:exitFadeDuration="@android:integer/config_mediumAnimTime">
    <item android:state_activated="true"
            android:drawable="@drawable/list_item_active_pattern"  />
    <item  android:drawable="@drawable/list_bg_pattern" />
</selector>
Run Code Online (Sandbox Code Playgroud)

当onItemClick(..)被调用时,请输入此代码.

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {   
            getListView().setItemChecked(position, true);
            getListView().setSelection(position);
            getListView().setSelected(true);

    }
Run Code Online (Sandbox Code Playgroud)

  • 只是为了帮助未来的读者,但如果你的目标api设置低于11,这将无法工作.其中一个兼容性功能是干扰. (2认同)