ListFragment multi-choice does not show selection

2019-05-27 12:43发布

问题:

I'm trying to implement the contextual action bar in my app. I'm extending a ListFragment and I have a custom ArrayAdapter and list item xml defined. Clicking on items works fine and the background color changes on the list item. Where I'm running into trouble is when selecting multiple items. The contextual action bar comes up and I can tell I'm actually selecting items when I touch them because I'm having it log which items are selected, but the background highlight color on the list item does not change! It seems like some other people were running into this problem when using the Fragments API as well and they had come up with a sort-of hack to get it to work properly. However, I was wondering if anyone has a definitive answer as to why my list doesn't show selected items.

For good measure, here's my code:

ListView list = getListView();
    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    list.setSelector(R.drawable.list_selector);

    // configure contextual action bar
    list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode actionMode, int position, long id, boolean b) {
            Log.i("debug", "item " + position + " changed state");
        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MenuInflater inflater = actionMode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);
            return true;  
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.delete:
                    Log.i("debug", "delete stuff");
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

回答1:

I provide my custom list item view with a background selector.

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<item android:state_activated="true" android:drawable="@drawable/number_bg_pressed" />
<item android:drawable="@android:color/transparent" />

I refer to APIdemos View/List/List16 example.



回答2:

I use android.R.layout.simple_list_item_activated_1 for layout when I set up SimpleCursorAdapter. Custom theme may be a better solution. In my case I have a static method to retrieve the layout depending on android api version.