notifyDataSetChanged Android ListView

人盡茶涼 提交于 2019-12-11 18:34:15

问题


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
}

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();
}

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;
  }

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);

How can i do this for delete button ?
Why notifyDataSetChanged() method doesn't work ?


回答1:


Do not re-create the object of ArrayList or Array you are passing to adapter, just modify same ArrayList or Array again. and also when array or arrylist size not changed after you modify adapter then in that case notifydatasetchange will not work.

In shot it is work only when array or arraylist size increases or decreases.




回答2:


I solve it to recreate everytime the adapter.
Not good solution but it's the only I've found.




回答3:


Try this

Adapter.clear()
for (HashMap <String,String> object : Session.getList())
Adapter.add(object)


来源:https://stackoverflow.com/questions/12378845/notifydatasetchanged-android-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!