关于 Android ListView 和 ArrayAdapter 的问题
所以我在这里玩弄这段代码,主要目标是单击按钮后用新项目更新列表。我的代码可以工作,但我不确定这是否是正确的方法。
我有两个方法。第一个方法采用我的 ArrayList,添加两个字符串并将其发布到列表视图。伟大的!
当我点击按钮时,会调用我的第二种方法。它添加了一个新字符串并更新了列表,但为了让我更新现有的列表视图,我必须再次执行“setListAdapter(new ArrayAdapter....”行,我不确定这是否正确 我可以使用一些输入,
谢谢!
方法 1:
static final List list = new ArrayList();
private void showEvents (Cursor cursor){
list.add("foo");
list.add("bar");
Log.d(TAG,"showevent");
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));
}
方法 2(当我点击 listView 下的按钮时调用此方法):
private void updateListView(){
try{
list.add("son");
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));
}catch (Exception e){
Log.d(TAG, "E="+e);
}
}
So I'm toying with this code here, and the main objective is to update a list with a new item once I click a button. The code I have works, but I'm not sure if it's the right way to do it.
I have two methods. The first method takes my ArrayList, add's two strings and posts it to the listview. Great!
The Second method I have is called when I tap on a button. It add's a new string and updates the list, but in order for me to update the existing listview, I had to do the "setListAdapter(new ArrayAdapter...." line again and I'm not sure if that's the right thing to do.
I can use some input please, thanks!
Method 1:
static final List list = new ArrayList();
private void showEvents (Cursor cursor){
list.add("foo");
list.add("bar");
Log.d(TAG,"showevent");
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));
}
Method 2 (this is called when I tap a button that is under the listView):
private void updateListView(){
try{
list.add("son");
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));
}catch (Exception e){
Log.d(TAG, "E="+e);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需再次设置列表适配器,而是在 ArrayAdapter 上调用 notificationDataSetChanged()。上面的代码将“起作用”,但它会强制整个 ListView 重新绘制,因此如果您有一个很长的列表并且用户已经滚动,它会将它们弹出到顶部。通知是一种更干净的方法。
非常简单的代码。在这种情况下,我在活动中引用了数组适配器:
这是基于您的代码的示例:
Rather than setting the list adapter again, call the notifyDataSetChanged() on the ArrayAdapter. The above will "work", but it forces the entire ListView to redraw, so if you have a long list and the user has scrolled it'll pop them back to the top. The notify is a cleaner way to do that.
Very simple code. I've got a reference to the array adapter in the activity in this case:
Here's and example based on your code:
为
ArrayAdapter
声明一个成员变量(例如myAdapter
),然后在showEvents
方法中初始化它并将其设置为 listView。将字符串添加到列表后,在updateListView
方法中,只需调用myAdapter.notifyDataSetChanged();
即可解决问题declare a member variable for the
ArrayAdapter
(saymyAdapter
) and then initialise it in theshowEvents
method and set it to the listView. next in theupdateListView
method after adding string to your list just callmyAdapter.notifyDataSetChanged();
and that should do the trick