Change background color of an item in Android ListActivity onListItemClick

后端 未结 6 1070
醉酒成梦
醉酒成梦 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:22

    Thanks heycosmo. your solution solved my problem.

    Have no clue why we should set background in 2 places.

    1. Adapter's getView()

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         ....
         ....
         ....
            if(arrayBools[position]) {
                view.setBackgroundColor(Common.colorBkgroundSelected);
            }
            else{
                view.setBackgroundColor(Common.colorBkgroundNormal);            
            } 
         ....
         ....
         ....
    }
    

    2. ListActivity's onListItemClick().

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
          super.onListItemClick(l, v, position, id);       
          arrayBools[position] = ( arrayBools[position] ? false : true );
    
         if(arrayBools[position]) {
             v.setBackgroundColor(colorBkgroundSelected);
         }
         else{
            v.setBackgroundColor(colorBkgroundNormal);          
         }    
    }
    

提交回复
热议问题