ListView: setItemChecked only works with standard ArrayAdapter - does NOT work when using customized ArrayAdapter?

前端 未结 4 1832
遇见更好的自我
遇见更好的自我 2020-12-04 16:35

This is really weird.

When I use the standard ArrayAdapter for a ListView calling setItemChecked works OK

But when using a custom made ArrayAdapter it does n

4条回答
  •  死守一世寂寞
    2020-12-04 17:22

    For sure you have to set the choice mode for your ListView, for example:

    list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    

    But if you're also using a custom layout for your list item (R.layout.drawing_list_item), then you have to make sure your layout implements the Checkable interface:

    public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
        private boolean isChecked = false;
    
        public CheckableRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public boolean isChecked() {
            return isChecked;
        }
    
        public void setChecked(boolean isChecked) {
            this.isChecked = isChecked;
            changeColor(isChecked);
        }
    
        public void toggle() {
            this.isChecked = !this.isChecked;
            changeColor(this.isChecked);
        }
    
        private void changeColor(boolean isChecked){
            if (isChecked) {
                setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
            } else {
                setBackgroundColor(getResources().getColor(android.R.color.transparent));
            }
        }
    }
    

    Then your checkable layout will be defined as the following example:

    
    
    
        
    
        
    
    
    

提交回复
热议问题