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);
这是我的适配器:
And this is my 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屋!