Erratic behaviour of listview (Android)

梦想与她 提交于 2020-01-24 22:58:49

问题


In my listview I have a custom Adapter, which I build using a TreeMap, I defined the getView method which is as follows. I am trying to strike out the text in a certian textview of the listview on click, only those textviews will be striken off which contain a certain pattern of characters (y@y). However on clicking one row in the listview I am getting strike out effect on some other row.

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);



        if (convertView == null) { 
            convertView = inflater.inflate(R.layout.chklistlayout, parent, false); 
        }
        TextView textView = ((TextView) convertView.findViewById(R.id.textView1));
        TextView imageview = ((TextView) convertView.findViewById(R.id.textView2));
        textView.setText(values[position]);
        imageview.setText(mValues[position]);


        String s = mValues[position];
        if (s.contains("y@y")) {
            System.out.println("In if of getview");
            System.out.println(s);
            imageview.setPaintFlags(imageview.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {

        }

        return convertView;
    }
}

I tried using a holder pattern too, using a static holder class, but the problem seems to persist. Any pointers?


回答1:


this answer is half mine and half from Muhammad Babar that we both commented on the question making together a quite nice answer:

use else block to handle this, imageview.setPaintFlags() not to strike

that happens

Because of the convertView. When you scroll the list the same view that was used before is give back to getView method. So the same imageView that you painted with StrikeThrough before is still painted with it. So you have to revert that action.

more over, because of this recycling, usually dealing with Adapters you must ALWAYS undo/revert/repaint/change text/change image to all the elements to make sure it will be on screen the way you want.

ps.: now you should apply a Holder pattern to get better performance.



来源:https://stackoverflow.com/questions/18589716/erratic-behaviour-of-listview-android

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