【问题标题】:how to prevent adding new view object in listview when scrolling listview滚动列表视图时如何防止在列表视图中添加新视图对象
【发布时间】:2019-02-15 04:15:19
【问题描述】:

我有一个线性布局内部列表视图,在线性布局内部我必须添加 ImageView 和 TextView 并在适配器中设置我想要显示的数据。 它完美地工作,直到列表视图滚动。 当我滚动 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;

【问题讨论】:

  • 附带说明,每次调用 getView() 方法时,您都会创建一个新的 ImageView 和 TextView。如果您的 ListView 包含超过 ~7 个项目,那么这将是非常低效的,并且从我所看到的情况来看甚至可能没有必要。此外,考虑使用 RecyclerView 作为 ListView 应被视为已弃用。

标签: android listview


【解决方案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);

【讨论】:

    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    相关资源
    最近更新 更多