Android - Any change made to any of the ListView item is affected to the first item

自作多情 提交于 2019-12-10 19:19:06

问题


I have a ListView which displays a list of items. When I click on an item, I mark the item as striked in my database table. Then, I update the list using a SimpleCursorAdapter, setViewBinder, setViewValue.

I check if the striked column is set for a corresponding item, and then I update the TextView to strike the item.

The code is below

Cursor c = db.fetchAllNotes(id);
    startManagingCursor(c);

    String[] from = new String[] { DatabaseHandler.KEY_LIST };
    int[] to = new int[] { R.id.text1 };

    SimpleCursorAdapter notes =
        new SimpleCursorAdapter(this, R.layout.task_row, c, from, to);

    notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            // TODO Auto-generated method stub      
            text = (TextView) view.findViewById (R.id.text1);
            System.out.println("Item is "+ text.getText().toString());
            System.out.println("Item from cursor is " + cursor.getString(2));
            System.out.println("Striked value is " + Integer.parseInt(cursor.getString(3)));
            if(Integer.parseInt(cursor.getString(3)) == 1)
                text.setPaintFlags(textViewItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            return false;
        }
    });
    setListAdapter(notes);

What am I doing wrong?


回答1:


I think it's because views are reused in ListView. Try to reset paint flags when view is not striked:

 if(Integer.parseInt(cursor.getString(3)) == 1){
     textViewItem.setPaintFlags(textViewItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
 } else {
     //resed paint flags
     textViewItem.setPaintFlags(textViewItem.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
 }

Edit: I am not sure if my explatation is corect. When You have 10 items on ListView and only 5 of them are visible android creates(inflantes) only 5 views. When you scroll list one new item will be visible but olso one will disapear so there will be one unused view. Android wil take that unused view, fill it with new data and use it for newly appeared item. I found some more info here.




回答2:


you need different types of rows in your list(two types, striked and non striked), here is the best explaination i found for myself

https://stackoverflow.com/a/4778062/579646



来源:https://stackoverflow.com/questions/11634673/android-any-change-made-to-any-of-the-listview-item-is-affected-to-the-first-i

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