在更新列表视图之后维护以前的项目

时间:2016-07-20 14:39:03

标签: android listview initialization updating notifydatasetchanged

我在更新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);

    }
}

1 个答案:

答案 0 :(得分:1)

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

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

    $file = '../..' . $r2['fileurl'] . $r2['filename'];
            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                readfile($file);
                exit;
            }
    
  2. 初始化public class MyActivity extends Activity{ private ListView mListView; private CustomListAdapterForPostOrgan mAdapter; private List<Posts> mPosts; } ,然后初始化适配器,然后在ArrayList的{​​{1}}中将其设置为ListView适配器一次。

    onCreate()
  3. 收到新数据后,首先将其添加到您的班级数组中,然后像这样调用Activity

    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);
    }