Listview and row selector not working

末鹿安然 提交于 2019-12-07 03:39:24

I've been playing around a little and I think I found a solution to your problem. This one works with list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

You can get the selected items via list.getCheckedItemPositions(). The only weird thing about it is, that in your selector you have to use android:state_activatedinstead of android:state_checked.

Activity code:

    ListView list = (ListView) findViewById(R.id.listView);

    // dummy values
    final String[] values = new String[] { "a", "b", "c", "d", "e", "f", "g",
            "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "w", "x", "y", "z" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            R.layout.row_contact, values){

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // View from recycle
            View row = convertView;

            // Handle inflation and make sure not to re-use a header view
            if (row == null) {
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.row_contact, null);
                row.setTag(position);

            }
            ((TextView)row.findViewById(R.id.txt_title)).setText(values[position]);
            return row;
        }

    };
    list.setAdapter(adapter);
    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

The selector (bg_row_contact.xml)

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@android:color/white" android:state_activated="false"/>
    <item android:drawable="@android:color/black" android:state_activated="true"/>

</selector>

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!