简体   繁体   中英

Android - Change color of multiple choice listview background

I have a multiple choice ListView which defaults as having a white background but when selected, the background of the item changes to blue (defined here by a hex code).

mItemState = new boolean[list.length];
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListOfMajors.this,android.R.layout.simple_list_item_multiple_choice,list);
mylist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mItemState[position] = !mItemState[position];
        if (mItemState[position]){
            view.setBackgroundColor(Color.parseColor("#33b5e5"));                                       
        }else{
            view.setBackgroundColor(Color.WHITE);                       
        }

    }

});

Right now, everything seems to be working fine. However, if I select the very first element, the very last element also changes background color (it does not get ticked however). Also, if I choose the very last element, the same thing happens to the very first element. What seem to be the reason that this happens?

Well you must be familiar with ListView recycling mechanism and convertView model. The last elements view is composed using first elements view as convertView . Consider this blog http://android.amberfog.com/?p=296 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM