ExpandableListAdapter onClickListener,调用notifyDataSetChanged()

时间:2015-07-03 18:23:28

标签: android expandablelistview onclicklistener expandablelistadapter

我有一个使用onclickListener来更改父文本的自定义适配器,我无法弄清楚如何让notifyDataSetChanged方法在适配器中工作。

应该发生的事情是我有一个可扩展的视图,当你点击子视图中的按钮时,它会用子视频更新父视图...

这是一个应该发生什么的图片示例。 在点击按钮之前使用这个: enter image description here

点击按钮后点击此处: enter image description here

"选择一种成分"更改为" Rice,cups"或点击的任何内容

所以在我显示的代码中,单击按钮后它应该更新父级,然后刷新视图,我出于某种原因无法做到这一点?

继承我的代码,提前致谢!

    package com.example.andrew.mypantry;

import android.content.Context; 
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.List;

/**
 * Created by andrew on 7/1/2015.
 */
public class IngExpandableListAdapter extends BaseExpandableListAdapter {

private Context context;
private List<String> listDataHeader; //header titles
//child data in format of <header title, child title>
private HashMap<String, List<String>> listDataChild;

public IngExpandableListAdapter(Context context, List<String> listDataHeader,
                                HashMap<String, List<String>> listDataChild) {
    this.context = context;
    this.listDataHeader = listDataHeader;
    this.listDataChild = listDataChild;
}

@Override
public Object getChild(int groupPosition, int childPosition) {
    return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosition);
}

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

private void test() {


    //notifyDataSetChanged();
    //super.notifyDataSetChanged();
    //this.notifyDataSetChanged();
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,
                         View convertView, ViewGroup parent) {
    final String childText = (String) getChild(groupPosition,childPosition);

    if (convertView == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.ingredient_list_item, null);
    }

    TextView txtListChild = (TextView) convertView.findViewById(R.id.ingredientContentTextView);

    txtListChild.setText(childText);

    //handle button
    Button ingredientButton = (Button)convertView.findViewById(R.id.useIngredient_button);
    ingredientButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //change header to ingredient selected
            listDataHeader.set(groupPosition, childText);
            //test();
        }
    });

    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
}

@Override
public Object getGroup(int groupPostion) {
    return this.listDataHeader.get(groupPostion);
}

@Override
public int getGroupCount() {
    return this.listDataHeader.size();
}

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

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {

    String headerTitle = (String) getGroup(groupPosition);

    if(convertView == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.ingredient_list_group, null);
    }

    //handle textView
    final TextView listHeader = (TextView) convertView.findViewById(R.id.ingredientGroupTextView);
    listHeader.setTypeface(null, Typeface.BOLD);
    listHeader.setText(headerTitle);

    //handle button
    Button deleteButton = (Button)convertView.findViewById(R.id.deleteButton);
    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //remove item from list
            Log.d("TESTING", "item should be removed");

        }
    });


    return convertView;
}

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

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

}

5 个答案:

答案 0 :(得分:4)

正如beworker所提到的,您的问题来自于使用错误的数据结构,这就是您的应用崩溃的原因。您正在使用标题标题作为哈希映射的键,当您在listDataHeader中修改标题时,修改正确适用于它,但不适用于哈希映射中的键对象。这意味着您的孩子仍然存在于hashmap内的旧标题键下,并且新标题键的值为null。因此,当您致电

时,您将获得NullPointerException
this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosition);

this.listDataChild.get(this.listDataHeader.get(groupPosition))

返回Null

解决方案是使用ArrayList作为标题标题和ArrayList&gt;为孩子。这两个数组列表中的关键是您的组索引。

答案 1 :(得分:3)

我认为问题出在您使用的数据结构中。保留在哈希表中分配给父名称的子项列表。当父母的名字在父母列表中更改时,哈希表中的旧子项分配将无效。

我建议您将SparseArray<List<String>>List<List<String>>用于listDataChild字段。它会将组位置直接映射到子列表。因此,在listDataHeader中更改父级名称不会破坏数据一致性,因为组位置将保持不变。现在,您应该能够安全地使用notifyDataSetChanged()方法来更新标头。

希望这有帮助。

答案 2 :(得分:0)

而不是使用notifyDataSetChanged();创建一个接口,数据来自哪里并实现它是你的适配器,然后改变该接口函数中父节点的值,因为getChildView()在每个子节点之后被调用将更新您的listview Parent。检查并验证我有同样的问题

假设您要将数据从适配器传输到适配器

adapter.java

public interface data { public void dataMethod(String data); }

并在adapter

中实施此方法

public void dataMethod(String data) { this.data = data; }

从getChildView()调用dataMethod()并更新我显示的字符串

并在适配器

中的getViewChild方法中设置数据

答案 3 :(得分:0)

正如@beworker已经提到的那样,你不应该将孩子存放在HashMap中。请改用ArrayList,然后按组索引访问子项。那就是你如何改变适配器。作为奖励,我实施了群组删除。

public class IngExpandableListAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<String> listDataHeader; //header titles
    private List<List<String>> listDataChild;

    public IngExpandableListAdapter(Context context, List<String> listDataHeader,
                                    HashMap<String, List<String>> listDataChild) {
        this.context = context;
        this.listDataHeader = listDataHeader;
        this.listDataChild = new ArrayList<List<String>>();
        for (String header : listDataHeader) {
            List<String> children = listDataChild.get(header);
            if (children == null) {
                children = Collections.emptyList();
            }
            this.listDataChild.add(children);
        }
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return this.listDataChild.get(groupPosition).get(childPosition);
    }

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

    @Override
    public View getChildView(final int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView,
                             ViewGroup parent) {
        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(this.context);
            convertView =
                    layoutInflater.inflate(R.layout.ingredient_list_item, null);
        }

        TextView txtListChild =
                (TextView) convertView.findViewById(R.id.ingredientContentTextView);
        txtListChild.setText(childText);

        //handle button
        Button ingredientButton =
                (Button) convertView.findViewById(R.id.useIngredient_button);
        ingredientButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //change header to ingredient selected
                listDataHeader.set(groupPosition, childText);
                notifyDataSetChanged();
            }
        });

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this.listDataChild.get(groupPosition).size();
    }

    @Override
    public Object getGroup(int groupPostion) {
        return this.listDataHeader.get(groupPostion);
    }

    @Override
    public int getGroupCount() {
        return this.listDataHeader.size();
    }

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {

        String headerTitle = (String) getGroup(groupPosition);

        if(convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(this.context);
            convertView =
                    layoutInflater.inflate(R.layout.ingredient_list_group, null);
        }

        //handle textView
        final TextView listHeader =
                (TextView) convertView.findViewById(R.id.ingredientGroupTextView);
        listHeader.setTypeface(null, Typeface.BOLD);
        listHeader.setText(headerTitle);

        //handle button
        Button deleteButton = (Button) convertView.findViewById(R.id.deleteButton);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //remove item from list
                Log.d("TESTING", "item should be removed");
                this.listDataHeader.remove(groupPosition);
                this.listDataChild.remove(groupPosition);
                notifyDataSetChanged();
            }
        });

        return convertView;
    }

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

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

答案 4 :(得分:0)

这是完全可行的解决方案。主要想法 - 不要在OnClickListener内使用Adapter,您必须改为使用ExpandableListView.setOnChildClickListener()

<强> MyFragment.java

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
        String[][] data = {
                {"Rice, cups", "Chiken, breasts", "Milk, gallons", "Beans, cups"},
                {"Orange, lemon", "Tomato, potato", "Onion, garlic"},
                {"Apple, pinapple", "Grapes, pear", "Cherry, berry", "Banana, strawberry", "Peach, apricot"},
        };

        final ChoiceAdapter adapter = new ChoiceAdapter(data);
        final ExpandableListView listView = new ExpandableListView(inflater.getContext());

        listView.setGroupIndicator(null);
        listView.setAdapter(adapter);
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                adapter.selectChild(groupPosition, childPosition);
                listView.collapseGroup(groupPosition);
                // NOTE you even don't need to call notifyDataSetChanged() if you call collapseGroup()
                // adapter.notifyDataSetChanged();
                return true;
            }
        });

        return listView;
    }
}

<强> ChoiceAdapter.java

import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.Arrays;

public class ChoiceAdapter extends BaseExpandableListAdapter {
    private final String[][] mData;
    private final int[] mChoice;

    public ChoiceAdapter(String[][] data) {
        mData = data;
        mChoice = new int[data.length];
        Arrays.fill(mChoice, -1);
    }

    @Override
    public int getGroupCount() {
        return mData.length;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mData[groupPosition].length;
    }

    @Override
    public Integer getGroup(int groupPosition) {
        return mChoice[groupPosition];
    }

    @Override
    public String getChild(int groupPosition, int childPosition) {
        return mData[groupPosition][childPosition];
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if (convertView == null) {
            // TODO inflate layout from xml instead
            convertView = new TextView(parent.getContext());
        }

        // TODO use ViewHolder pattern instead
        TextView textView = (TextView) convertView;
        textView.setTypeface(null, Typeface.BOLD);

        int childPosition = getGroup(groupPosition);
        if (childPosition < 0) {
            textView.setText("Choose an ingredient");
        } else {
            textView.setText(getChild(groupPosition, childPosition));
        }

        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        if (convertView == null) {
            // TODO inflate layout from xml instead
            convertView = new TextView(parent.getContext());
        }

        // TODO use ViewHolder pattern instead
        TextView textView = (TextView) convertView;
        textView.setText(getChild(groupPosition, childPosition));

        return convertView;
    }

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

    public void selectChild(int groupPosition, int childPosition) {
        mChoice[groupPosition] = childPosition;
    }

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

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

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