【问题标题】:Android notifyDataSetChanged() does not workAndroid notifyDataSetChanged() 不起作用
【发布时间】:2016-05-03 13:13:18
【问题描述】:

我已经阅读了很多关于这个问题的帖子,但我找不到解决方案。

myAdapter.notifyDataSetChanged();我的 ExpandableListView 的 (BaseExpandableListAdapter) 没有更新它的内置方法:getChildView()。

提前致谢!

代码: 这是我的适配器类:

public class MyAdapter extends BaseExpandableListAdapter {
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    String title = (String) this.getChild(groupPosition, childPosition);
    if (convertView == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if ( groupViewType[groupPosition] == 0) {
                Log.d("MyAdapter", "getChildView: setting child_layout");

                convertView = layoutInflater.inflate(R.layout.child_layout, null);

            } else {
                Log.d("MyAdapter", "getChildView: setting exercise_layout");

                convertView = layoutInflater.inflate(R.layout.exercise_layout, null);

            }
    }
    return convertView;
}

   // To alternate between layouts when swiping to the right or left.
public void updateView(int groupPosition) {

    if (groupViewType[groupPosition] == 1) {
        Log.d("MyAdapter", "UpdateView: from 1 to 0");
        groupViewType[groupPosition] = 0;
    }
    else {
        Log.d("MyAdapter", "UpdateView: from 0 to 1");
        groupViewType[groupPosition] = 1;
    }
}

这是我在其中调用 MyAdapter 的 MainActivity 类:

expandableListView = (ExpandableListView) findViewById(R.id.expListView);
final MyAdapter myAdapter = new MyAdapter(this,  Headings, ChildList);
expandableListView.setAdapter(myAdapter);

expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {
            myAdapter.updateView(groupPosition); // This method works fine!
            myAdapter.notifyDataSetChanged();  // It doesn't change the view in getChildView();
            return false;
        }
    });

解决方案: 我通过设置 convertView = null; 解决了这个问题getChildView() 中的 if 语句之前。

对不起。

【问题讨论】:

  • 什么?您将其设置为空,然后在下一行检查它是否为空?这似乎违反直觉......
  • 是的,你完全正确,哈哈。但是,我的方法有什么问题吗?
  • 你真的应该使用视图持有者模式。虽然这段代码在技术上没有任何问题,但视图持有者模式是使用列表视图时的最佳实践。我强烈推荐观看这个关于 listview 的 Google IO 讨论 youtube.com/watch?v=wDBM6wVEO70
  • 但是那样的话我不能实时更新视图,对吧?

标签: android adapter expandablelistview


【解决方案1】:

您必须使用 ViewHolder 模式才能正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2014-03-03
    相关资源
    最近更新 更多