简体   繁体   English

Android-更改多选ListView背景的颜色

[英]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). 我有一个多选ListView,默认情况下它具有白色背景,但是当被选中时,该项的背景会变为蓝色(在此由十六进制代码定义)。

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. 好吧,您必须熟悉ListView回收机制和convertView模型。 The last elements view is composed using first elements view as convertView . 最后一个元素视图是使用第一个元素视图作为convertView组成的。 Consider this blog http://android.amberfog.com/?p=296 . 考虑此博客http://android.amberfog.com/?p=296

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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