【问题标题】:Maintaining the previous items after the update listview更新listview后维护之前的item
【发布时间】:2023-06-07 19:41:02
【问题描述】:

我在更新 ListView 时遇到问题。我不想在第一次初始化后丢失我的ListView 的数据。 我在此站点和其他一些站点上进行了搜索,并找到了不同的解决方案。最后我使用了下面的代码,但我没有得到任何结果。

private void handelpost(List<Posts> posts,Page pages) {
    ListView listView;
    final CustomListAdapterForPostOrgan adapter;
    if (pages.getCurrentPage() > 1) {

        listView = (ListView) findViewById(R.id.lv_for_post_organ);
        adapter = new CustomListAdapterForPostOrgan(this, posts);

        adapter.notifyDataSetChanged();
        listView.setAdapter(adapter);

    } else {

        listView = (ListView) findViewById(R.id.lv_for_post_organ);
        adapter = new CustomListAdapterForPostOrgan(this, posts);



        listView.setAdapter(adapter);

    }
}

【问题讨论】:

  • 这些代码块的区别仅在于 notifyDataSetChanged,在这种情况下没有用。你能解释更多细节吗?你能告诉我为什么你在这里使用适配器初始化吗?这个方法只调用一次吗?或者你每次都重新创建适配器?
  • 我有一个列表视图,在每个连接中接收 2 个项目。我想在每次收到新数据时上传我的列表视图,同时我不想丢失以前的数据。这是我第一次,我没有任何经验。仅此而已,不再赘述。请你帮帮我。

标签: android listview initialization updating notifydatasetchanged


【解决方案1】:

您每次都在使用新数据创建新适配器。当您使用分页时,这是不可取的。您需要进行以下更改。

  1. 声明您的适配器和列表视图以及 ArrayList 类级别。

    public class MyActivity extends Activity{
         private ListView mListView;
         private CustomListAdapterForPostOrgan mAdapter;
         private List<Posts> mPosts;
    }
    
  2. 初始化您的ArrayList,然后是Adapter,然后在onCreate() of Activity 中将其设置为ListView 的适配器。

    private void onCreate(Bundle savedInstanceState) {
          super.onCreate();
    
          //After you've called setContentView() etc etc.
          mPosts = new ArrayList();
          mListView = (ListView) findViewById(R.id.lv_for_post_organ);
          mAdapter = new CustomListAdapterForPostOrgan(this, mPosts);
          mListView.setAdapter(mAdapter);
    }
    
  3. 当您收到新数据时,首先将其添加到您的类级数组中,然后像这样调用notifyDataSetChanged()

    private void handelpost(List<Posts> posts,Page pages) {
          //add new posts to existing array..
          mPosts.addAll(posts);
          //since adapter already has your array, simply make it refresh.
          mAdapter.notifyDataSetChanged();
    }
    

【讨论】:

  • //因为适配器已经有你的数组,只需让它刷新。
  • 你能解释一下吗//因为适配器已经有了你的数组,只需让它刷新。
  • 您在创建适配器CustomListAdapterForPostOrgan(this, mPosts);时已经在适配器中传递了数组mPost