简体   繁体   中英

Change item background color in simple listView

I would like to change an item background color when clicked, in a simple listView. Here's my code:

boolean[] selectedItem = new boolean[listElement.length]
final ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, listElement);
final ListView mylist = (ListView) findViewById(R.id.listView);
final ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list1);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {

            int firstVisiblePosition = mylist.getFirstVisiblePosition();
            int effectivePosition = pos - firstVisiblePosition;

            if (!selectedItem[pos]) {
                mylist.getChildAt(effectivePosition).setBackgroundColor(Color.parseColor("#66F44336"));
            } else {
                mylist.getChildAt(effectivePosition).setBackgroundColor(Color.parseColor("#EEEEEE"));
            }

           selectedItem[pos] = !selectedItem[pos];
        }
    });

When the list is short (no scroll involved) it works, when it's long it does not: the background color of the clicked item does change, but when I start to scroll the background color of every item starts to change, and I can't find any logic in those changes, they change and reverse without me even touching them, just by scrolling, wich is strange since the color should only change when onItemClick() is called, right? What am I missing?

You're missing the point that the ListView re-uses its item layouts when they go out of screen (ie you scroll the list).

You need to save the background for each of your item and set it once the view is requested. That happens inside of ListView adapter's getView .

A quick fix would be to use a custom adapter on the go:

final boolean[] selectedItem = new boolean[listElement.length];

ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
        android.R.layout.simple_list_item_1, list1) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if (selectedItem[position]) {
            view.setBackgroundColor(Color.parseColor("#66F44336"));
        } else {
            view.setBackgroundColor(Color.parseColor("#EEEEEE"));
        }
        return view;
    }
};

This lacks error checking but you should get the idea. Good luck!

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