notifyDataSetChanged Android ListView [英] notifyDataSetChanged Android ListView
问题描述
我的应用程序类中有一个项目列表:
I have a list of items in my Application class:
public class MyApp extends Application {
private static ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//GET AND SET
}
我想在 ListView 中使用它.我有一个按钮可以在 MyApp 列表中添加一个元素:
I would to use it in ListView. I have a button to add one element in MyApp list:
public void addBase(View view){
MyApp.add2List(....); //add to MyApp.list
adapter.notifyDataSetChanged();
}
在同一个活动中,我设置了 ListView:
And in the same activity I set ListView:
list=(ListView)findViewById(R.id.list_view);
adapter=new MyListAdapter(this, R.layout.list_item, Session.getList());
list.setAdapter(adapter);
这是我的适配器:
public class MyListAdapter extends ArrayAdapter<HashMap<String, String>> {
private Context _context;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public MyListAdapter(Context context, int resourceId, ArrayList<HashMap<String, String>> items) {
super(context, resourceId, items);
this.data = items;
_context = context;
activity = ((Activity)context);
inflater = activity.getLayoutInflater();
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
final ArrayList<HashMap<String, String>> list = Session.getList();
if(convertView==null){
vi = inflater.inflate(R.layout.list_item, null);
ImageButton delete = (ImageButton)vi.findViewById(R.id.delete_item);
delete.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
list.remove(position);
notifyDataSetChanged();
}
});
}
return vi;
}
我使用了 notifyDataSetChanged() 方法,但它不起作用!!列表视图没有更新.
如果再次尝试创建适配器,添加按钮将起作用.
I used notifyDataSetChanged() method, but it doesn't work !! No update to listview.
If try to create adapter again, the add button work.
adapter=new MyListAdapter(this, R.layout.list_item, Session.getList());
list.setAdapter(adapter);
如何为删除按钮执行此操作?
为什么notifyDataSetChanged() 方法不起作用?
How can i do this for delete button ?
Why notifyDataSetChanged() method doesn't work ?
推荐答案
我解决了每次重新创建适配器.
不是很好的解决方案,但这是我唯一找到的.
I solve it to recreate everytime the adapter.
Not good solution but it's the only I've found.
这篇关于notifyDataSetChanged Android ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!