Change item background color in simple listView

夙愿已清 提交于 2020-02-06 08:08:04

问题


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?


回答1:


You're missing the point that the ListView re-uses its item layouts when they go out of screen (i.e. 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!



来源:https://stackoverflow.com/questions/30424912/change-item-background-color-in-simple-listview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!