android listview有时只会更新

时间:2014-08-12 02:48:05

标签: android android-layout

我的android程序中有一个listview,它从ArrayList适配器获取信息。 我有三个方法调用listview.invalidateViews()。

其中两种方法可以正常工作,第三种方法似乎冻结了listview。退出活动并在屏幕上旋转时,信息会正确保存。但是如果不采取这些行动,列表视图就不会更新。

任何想法?

更新:

这些实例有效:

public void onItemClick(AdapterView<?> a, View v, int index, long id) {
    al.remove(index);
    adapter.notifyDataSetChanged();
}

public void addToList(View view) {
    EditText et = (EditText) findViewById(R.id.ListText1);
    if (et.getText().toString().equals("")) {
        //do nothing
    }
    else { 
        al.add(et.getText().toString());
        adapter.notifyDataSetChanged();
        et.setText(null);
    }
}

此方法不起作用:

public void resetList(View view) {
    al = new ArrayList<String>();
    adapter.notifyDataSetChanged();
}

1 个答案:

答案 0 :(得分:0)

您使用invalidateViews()的方式有所不同,如果您想更改listview's child的视图,那么您可以使用invalidateViews()但是如果您要更改listview's adapte的数据/内容1}}你需要使用notifyDataSetChanged()方法。

question

中讨论了两者的区别

<强> ListView.invalidateViews()

 is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.

<强> Adapter.notifyDataSetChanged()

on the other hand, is to tell the observer of the adapter that the contents of what is being adapted have changed. Notifying the dataset changed will cause the listview to invoke your adapters methods again to adjust scrollbars, regenerate item views, etc...

并使用您的方法

public void resetList(View view) {
    al = new ArrayList<String>();
    adapter.notifyDataSetChanged();
}

制作ArrayList<String>();的新对象不会重置列表视图的数据。只是因为您在适配器上传递的al ArrayList现在与您的al = new ArrayList<String>();不同,您现在需要做的就是访问当前的arraylist,然后使用al.clear()方法清除其内容。< / p>

相关问题