【问题标题】:notifyDataSetChanges for list adapter, modify only part of the view列表适配器的 notifyDataSetChanges,只修改部分视图
【发布时间】:2015-06-05 11:15:15
【问题描述】:

这可能是个奇怪的问题,我知道这里是否会被否决

所以我有一个自定义适配器(使用 ViewHolder 模式),它有这样的视图:

    private class ViewHolder {
        ImageView chatImage;
        TextView chatName;
        TextView lastMessage;
        TextView lastMessageTime;
        TextView unreadMessagesCount;
        //ViewStub avatarsViewStub;
    }

    private ViewHolder createViewHolder (View view) {
        ViewHolder holder = new ViewHolder();
        holder.chatImage = (ImageView) view.findViewById(R.id.chat_image);
        holder.chatName = (TextView) view.findViewById(R.id.chat_participant_name);
        holder.lastMessage = (TextView) view.findViewById(R.id.last_message);
        holder.lastMessageTime = (TextView) view.findViewById(R.id.last_message_time);
        holder.unreadMessagesCount = (TextView) view.findViewById(R.id.unread_messages_count);
        return holder;
    }

TextView unreadMessagesCount 应该显示未读消息的数量,并且每当有新消息出现时都应该更新。但正如你所看到的,有很多 Views,我的目标是:只更新 unreadMessagesCount 而不是在调用 adapter.notifyDataSetChanges() 时调用整个 getView,我想知道这是否可能

编辑:我已经发布了我当前的解决方案作为答案之一,但我们仍在寻找更好的方法

【问题讨论】:

  • 我认为这不可能。不过我有兴趣知道

标签: android listview baseadapter


【解决方案1】:

您只能更新ListView 的列表项中所需的视图。通过使用以下方法,您可以查看给定位置的列表项。

public View getViewByPosition(int position) {
    final int firstListItemPosition = filesListview.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + filesListview.getChildCount() - 1;
    if (position < firstListItemPosition || position > lastListItemPosition) {
        // return filesListview.getAdapter().getView(position, filesListview.getChildAt(position), filesListview);
        return null;
    } else {
        final int childIndex = position - firstListItemPosition;
        return filesListview.getChildAt(childIndex);
    }
}

获取特定位置的视图后,您可以使用getTag() 获取ViewHolder 并更新数据。

View listItem = getViewByPosition(position);
if(listItem!=null){
    ViewHolder holder = (ViewHolder)view.getTag();
   //Update the data
}

【讨论】:

  • 它似乎不会在没有 notifyDataSetChanged() 调用的情况下更新 UI,我丢失了什么吗?我通过在 Fragment 类中获取 View 来更改 UI(其中存储 listView)
  • 不,它是一个工作示例,我已经在没有 notifyDataSetChanged() 的情况下尝试过,如果给定位置的视图可见,上述方法将返回列表项的视图,否则将返回 null。
  • 在执行此操作时,您需要更新与 ListAdapter 关联的列表中的数据,以保持数据一致,
  • 好的,告诉我你的问题在哪里?该方法是返回任何视图还是返回 null?
  • 当我改变它时,改变不会出现,直到 notifyDataSetChanges 被调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多