我有一个列出一套书籍的ListView 用户可以添加新书,然后使用onActivityResult方法再次显示书籍集。
在添加一本新书之后,我已经花了好几个小时来刷新这套书,但根本没有运气。
这是我尝试过的代码:
public class BookActivity extends Activity {
private ArrayList<Book> books = null;
private BookItemAdapter bookItemAdapter;
ListView booksSetView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
books = new ArrayList<Book>();
booksSetView = (ListView)findViewById(R.id.booksSet);
Cursor booksCursor = null;
booksCursor = getBooksCursor();
if (booksCursor.moveToFirst())
{
do
{
books.add(getBookFromCursor(booksCursor));
} while(booksCursor.moveToNext());
}
bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
booksSetView.setAdapter(bookItemAdapter);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.e("BOOKS MANAGER", "trying to refresh");
bookItemAdapter.notifyDataSetChanged();
booksSetView.invalidate();
booksSetView.invalidateViews();
}
}
请帮忙。
非常感谢!
答案 0 :(得分:5)
这对我有用
Adapter adapter = list.getAdapter();
list.setAdapter(null);
list.setAdapter(adapter);
它强制notifyDataSetChanged被触发,它就像一个魅力!
答案 1 :(得分:1)
我没有看到你在哪里更新书籍ArrayList,这是ListView背后的数据。如果你在onActivityResult中更新该对象,那么它应该可以正常工作。
答案 2 :(得分:0)
我有这样奇怪的问题,虽然它真的不漂亮,你可以用notifyDataSetChanged代替适配器构造函数。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.e("BOOKS MANAGER", "trying to refresh");
bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
booksSetView.setAdapter(bookItemAdapter);
}
答案 3 :(得分:0)
list.setAdapter(list.getAdapter());
更快更简单的解决方案