我的应用程序类中有一个项目列表:
public class MyApp extends Application {
private static ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//GET AND SET
}
我会在 ListView 中使用它。我有一个按钮可以在 MyApp 列表中添加一个元素:
public void addBase(View view){
MyApp.add2List(....); //add to MyApp.list
adapter.notifyDataSetChanged();
}
在同一个活动中,我设置了 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()方法,但它不起作用!没有更新列表视图。
如果尝试再次创建适配器,添加按钮将起作用。
adapter=new MyListAdapter(this, R.layout.list_item, Session.getList());
list.setAdapter(adapter);
我该如何为删除按钮执行此操作?
为什么 notifyDataSetChanged() 方法不起作用?