当用作expandablelistview子

时间:2017-08-05 18:20:40

标签: android expandablelistview expandablelistadapter

我有一个ExpandableListView,它使用一些EditTextViews作为子项,如下所示:

enter image description here

问题是当我在其中一个EditText字段中输入内容并关闭该组时,内容会在一个单独的组中或有时在两个组中重复。

我的适配器只返回固定数量的子视图,这里是代码:

public class MyAdapter extends BaseExpandableListAdapter {
    @Override
    public int getGroupCount() {
        return 3;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return 1;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        //Inflate layout and return rowView

        return rowView;
    }

    @Override
    public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        //Inlfate layout and return rowView
        return rowView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}

我尝试过使用ViewHolder并获得相同的结果。我需要做些什么来防止内容被复制?

1 个答案:

答案 0 :(得分:0)

我意识到ExpandableListView的问题是每次展开子视图时都会调用getChildView。这会导致视图重复使用。

要解决这个问题,我通过膨胀子视图布局并创建一个HashMap来存储EditText

的值来禁用视图回收
private  String title;

private  HashMap<String, String> holder = new HashMap<>();

public MyAdapter(String title){
    this.title = title;
}

然后在getChildView方法中执行以下操作:

@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_child, parent, false);

    final EditText etFirstName = (EditText) convertView.findViewById(R.id.et_first_name);
    final String value =  holder.get(String.valueOf(groupPosition + childPosition));

    etFirstName.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            holder.put(String.valueOf(groupPosition + childPosition), s.toString());
        }
    });

    if (value != null){
        etFirstName.setText(value);
    }

    return convertView;
}

要为多个视图启用相同的功能,您可以创建模型对象并使用groupPosition + childPosition作为HashMap的键。