ListView元素未被选中

时间:2013-12-05 12:54:20

标签: android listview

我有一个ListViewFragment类,配置为choice_mode_single。我使用自定义CursorAdapter来填充listView。问题是当我从LV中选择某些东西时,它不会被蓝色背景突出显示。但是,只有文字变得粗体。代码:

public class CategoryFragment extends ListFragment{

int lastPosition;
DatabaseControl db;
OnCategorySelectedListener callBack;
CategoryCursorAdapter cursorInstance;
public interface OnCategorySelectedListener{

    public void onCategorySelected(int categoryName);   
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    db=new DatabaseControl(this.getActivity());
    db.open();
    getListView().setFastScrollEnabled(true);
    cursorInstance=new CategoryCursorAdapter(getActivity(), db.getCategoryCursor(""), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER, "category_name",0, db);
    getListView().setAdapter(cursorInstance);

    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    this.setListShown(true);

    this.getListView().setOnItemLongClickListener(listViewLongClick);
    if(savedInstanceState!=null)
        getListView().setItemChecked(savedInstanceState.getInt("position"), true);

}




@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    try{
        callBack=(OnCategorySelectedListener) activity;
    }

    catch(ClassCastException e){

        throw new ClassCastException(activity.toString()+" must implement OnCategorySelectedListener");
    }
}


@Override
public void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
    outState.putInt("position", lastPosition);

}

1 个答案:

答案 0 :(得分:0)

按照步骤创建ListView选择器

  • 首先,您必须在ListView行的可绘制文件夹中创建一个选择器,如
  

list_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@android:color/white" android:state_activated="true"/>
   <item android:drawable="@android:color/black"/>
</selector>
  • 然后将list_selector.xml应用于ListView行的父视图作为背景。

  • 然后使用mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE)

  • 将ListView设置为ListView.CHOICE_MODE_SINGLE

所以,你的最终代码就像是,

  mListView = (ListView) findViewById(R.id.listView);
  mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  MyAdapter mAdapter = new MyAdapter();
  mListView.setAdapter(mAdapter);
  mListView.setSelection(0);         // setting 0th position selected by default
  mListView.setItemChecked(0, true);

您还可以查看我的demo example from github