Android ListView listSelector not working

不羁的心 提交于 2019-12-06 14:10:09
Drew

I had similar problem. Sorry, cannot comment, so I post a possible answer.

  1. Remove android:listSelector="@drawable/list_selector_color" property from your ListView declaration

  2. In your R.layout.listview_bell_items specify your custom selector for a root layout. E.g., if root layout of your list item is RelativeLayout, try:
    <RelativeLayout ... android:background="@drawable/listitem_selector">...

The same goes for any other type of Layout.

If this still still does not give you the result you want, provide more details.

Update Ok, if nothing else helps, there's a temporary dirty workaround of your problem. I do not see why it would not work.

Introduce a selectedPos variable holding currently selected item.

private class MyAdapter extends .../*your base adapter*/ {                
    private static final int NOT_SELECTED = -1;
    private int selectedPos = NOT_SELECTED;

    // if called with the same position multiple lines it works as toggle
    public void setSelection(int position) {
        if (selectedPos == position) {
            selectedPos = NOT_SELECTED;
        } else {
            selectedPos = position;
        }
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if (position == selectedPos) {
            // your color for selected item
            view.setBackgroundColor(Color.parseColor("#000000"));
        } else {
            // your color for non-selected item
            view.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
        return view;
    }
}

Now, add the following code after you create and set ListView's adapter:

final MyAdapter adapter = new MyAdapter(...);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        adapter.setSelection(position);
    }
});

That is what I found out:

To get the list selector working the are two approaches:

1) You use the OnItemClickListener. Then the list selector drawable/color will work as expected when set it on the list view. Then you may use a TouchListener for getting ClickEvents of any child view instead of using a ClickListener.

2) You have set ClickListener on any child of the row view. In this case the list selector will not work when been set on the list view, so you have to set your list selector drawable/color as background of the row view.

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