如何防止滚动列表视图时在列表视图中添加新的视图对象

时间:2019-02-15 04:15:20

标签: android listview

我有一个linearLayout内部列表视图,在linearlayout内部,我必须添加ImageView和TextView,并且它在Adapter中设置了我想要显示的数据。 直到列表视图滚动,它才能正常工作。 滚动listView时,每次滚动时对象视图都会增加。 这是我的代码

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.chattemplate, null);
    }
    LinearLayout lin = (LinearLayout) convertView.findViewById(R.id.linearChat);
    final ImageView img1 = new ImageView(context);
    final TextView tv1 = new TextView(context);
        tv1.setText(chat.getPesan());
        tv1.setBackgroundResource(R.drawable.rounded_corner1);
        tv1.setPadding(10,10,10,10);
        tv1.setTextColor(context.getResources().getColor(R.color.white));
        tv1.setMaxWidth(250);
        img1.setImageDrawable(context.getResources().getDrawable(R.drawable.cservice));

        lin.addView(img1);
        lin.addView(tv1);

    return convertView;

1 个答案:

答案 0 :(得分:1)

您只需删除视图,然后添加新视图。

LinearLayout lin = (LinearLayout) convertView.findViewById(R.id.linearChat);
lin.removeAllViews();// here we remove all views before adding new views,
    final ImageView img1 = new ImageView(context);
    final TextView tv1 = new TextView(context);
        tv1.setText(chat.getPesan());
        tv1.setBackgroundResource(R.drawable.rounded_corner1);
        tv1.setPadding(10,10,10,10);
        tv1.setTextColor(context.getResources().getColor(R.color.white));
        tv1.setMaxWidth(250);
        img1.setImageDrawable(context.getResources().getDrawable(R.drawable.cservice));

        lin.addView(img1);
        lin.addView(tv1);