【问题标题】:Custom adapter replaces old items when adding new自定义适配器在添加新项目时替换旧项目
【发布时间】:2014-06-15 07:31:46
【问题描述】:

我的自定义列表适配器有问题。 我的主要活动包括 ListView、Button 和 EditText 字段。 当用户在 EditText 字段中输入内容并按下按钮时。正文应 出现在 ListView 中。对于 ListView,我制作了一个自定义适配器。目前只包含一个TextView,但我稍后会添加更多东西,所以我不能使用标准适配器。

问题在于,当用户键入内容并按下按钮时,字符串被放置在 ListView 中(太好了!),但问题是当用户再次按下时,旧文本被新文本替换(列表有 2 项,都包含相同的文本)。当用户将第三个项目添加到列表中时,该项目会替换旧项目,而我现在在列表中有 3 个最新项目?

所以问题是最新的项目取代了旧的?

在我的 mainActivity 我有这个:

private ListView list_messages;
private Button send_button;
private TextView input_message;

public Custome_list_item adapter;
public ArrayList<String> message_holder;

message_holder = new ArrayList<String>();
adapter = new Custome_list_item(this,message_holder);
list_messages.setAdapter(adapter);

自定义列表适配器只有一个getView,像这样:

LayoutInflater inflater = context.getLayoutInflater();

View rowView= inflater.inflate(R.layout.list_row, null, true);

TextView txtTitle = (TextView) rowView.findViewById(R.id.message_in_list_row);
ImageView imageView = (ImageView) rowView.findViewById(R.id.user_profile);
TextView timeView = (TextView) rowView.findViewById(R.id.date_and_time);

txtTitle.setText(message_holder.get(message_holder.size()-1));

//imageView.setImageResource(imageId);
timeView.setText("DD:MM:YY");
return rowView;

当用户点击主活动中的按钮时,我会这样做:

mainActivity.message_holder.add(item);

mainActivity.adapter.notifyDataSetChanged();

感谢任何帮助

【问题讨论】:

    标签: android listview android-listview adapter


    【解决方案1】:

    您的 getview 在 .get 函数中使用 size ,因此它将始终将数组中的最后一个字符串作为文本返回。它应该使用传入调用的位置。

    【讨论】:

    • 因为对于 ListView 的每个可见索引都会调用 getView。该函数的目的是在屏幕刷新时(由于无效、滚动或 notifyDataSetChanged)填充该视图的数据。
    • 顺便说一下,您的 getView 函数应该检查传入的视图(convertView)是否为空。如果非null,则不应该增加一个新的,而应该只填写数据(视图可以重复使用,并且应该是为了提高效率)
    【解决方案2】:

    尝试改变

    txtTitle.setText(message_holder.get(message_holder.size()-1));
    

    txtTitle.setText(message_holder.get(position));
    

    因为position 会将视图的位置替换为项目,即在第一个项目上,将显示来自第一个适配器位置的txtTitle。在第二个 listItem 上,将显示第二个适配器视图,依此类推。

    【讨论】:

    • @user3741818 乐于助人,享受编码。
    猜你喜欢
    • 2014-03-17
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    相关资源
    最近更新 更多