Change background color of an item in Android ListActivity onListItemClick

后端 未结 6 1053
醉酒成梦
醉酒成梦 2021-02-14 09:12

I know it sounds very simple, and there are questions about this. But none of it could solve my problem. So here we go:

I want to change background color of a list item

6条回答
  •  星月不相逢
    2021-02-14 09:19

    Sure thing. I would do this in the getView() method of a custom ListAdapter.

    MyAdapter extends SimpleAdapter {
        private ArrayList coloredItems = new ArrayList();
    
        public MyAdapter(...) {
            super(...);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
    
            if (coloredItems.contains(position)) {
                v.setBackgroundColor(Color.CYAN);
            } else {
                v.setBackgroundColor(Color.BLACK); //or whatever was original
            }
    
            return v;
        }
    }
    

    Update coloredItems when a list item is clicked.

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        if (coloredItems.contains(position)) {
            //remove position from coloredItems
            v.setBackgroundColor(Color.BLACK); //or whatever was original
        } else {
            //add position to coloredItems
            v.setBackgroundColor(Color.CYAN);
        }
    }
    

提交回复
热议问题