【问题标题】:notifyDataSetChanged Android ListViewnotifyDataSetChanged Android ListView
【发布时间】:2012-09-11 22:27:07
【问题描述】:

我的应用程序类中有一个项目列表:

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() 方法不起作用?

【问题讨论】:

  • 试试Session.getList().add(...)
  • 我的 add2List() 方法做到了。在删除方法中我试过了,但没有。

标签: android arraylist android-listview


【解决方案1】:

不要重新创建传递给适配器的 ArrayList 或 Array 的对象,只需再次修改相同的 ArrayList 或 Array。并且当您修改适配器后数组或 arrylist 大小未更改时,在这种情况下 notifydatasetchange 将不起作用。

在镜头中,仅当数组或数组列表大小增加或减少时才有效。

【讨论】:

  • 不要让你的整个帖子再次像这样粗体
【解决方案2】:

我解决它以重新创建每次适配器。
不是很好的解决方案,但这是我找到的唯一解决方案。

【讨论】:

  • 这不是标准的编程习惯。
【解决方案3】:

试试这个

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

【讨论】:

  • 这不是处理适配器的正确方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 2013-01-08
  • 2011-09-16
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多