Android 如何从string.xml中的字符串数组向ExpandableListView添加子级?
我想从string.xml中的字符串数组为ExpandableListView中的不同组添加不同的child,但我不知道该怎么做。Android 如何从string.xml中的字符串数组向ExpandableListView添加子级?,android,expandablelistview,Android,Expandablelistview,我想从string.xml中的字符串数组为ExpandableListView中的不同组添加不同的child,但我不知道该怎么做。 以下是string.xml的内容: <resources> <string name="app_name">app_name</string> <string-array name="child_group_1"> <item>Item1</item>
以下是string.xml的内容:
<resources>
<string name="app_name">app_name</string>
<string-array name="child_group_1">
<item>Item1</item>
<item>Item2</item>
<item>Item3</item>
<item>Item4</item>
<item>Item5</item>
</string-array>
<string-array name="child_group_2">
<item>Item1</item>
<item>Item2</item>
<item>Item3</item>
<item>Item4</item>
<item>Item5</item>
</string-array>
</resources>
Group.java:
public class Group {
private String title;
public Group(){
title="title";
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title=title;
}
}
我尝试了多种方法将孩子添加到小组中,但根本没有效果,希望有人能帮助我。尝试以下方法:
//Add some child
childs = new ArrayList<>();
for(int i=1; i<=getGroupCount(); i++){
String[] tmpGroup = mContext.getResources().getStringArray(mContext.getResources().getIdentifier("child_group_"+i,
"array", mContext.getPackageName()));
ArrayList<Child> valuesEAL = new ArrayList<>();
for(int j=0; j<tmpGroup.length; j++){
Child child = new Child();
child.setTitle(tmpGroup[j]);
valuesEAL.add(child);
}
childs.add(valuesEAL);
}
非常感谢你!!它完美地解决了我的问题。我还有另一个问题,我怎样才能得到用户点击的孩子的标题,我应该使用什么监听器?你可以在活动中使用上面显示的方法,或者在适配器中处理事件,就像我这里的示例:快乐编码!!单击child时出错,错误消息:java.lang.ClassCastException:android.widget.ExpandableListConnector无法转换为com.zhanhoshing.mtrstadic.myAdapter更新了答案。
public class Group {
private String title;
public Group(){
title="title";
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title=title;
}
}
//Add some child
childs = new ArrayList<>();
for(int i=1; i<=getGroupCount(); i++){
String[] tmpGroup = mContext.getResources().getStringArray(mContext.getResources().getIdentifier("child_group_"+i,
"array", mContext.getPackageName()));
ArrayList<Child> valuesEAL = new ArrayList<>();
for(int j=0; j<tmpGroup.length; j++){
Child child = new Child();
child.setTitle(tmpGroup[j]);
valuesEAL.add(child);
}
childs.add(valuesEAL);
}
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
MyAdapter adapter = (MyAdapter)expandableListView.getExpandableListAdapter();
String clickedChildTitle = ((Child)adapter.getChild(i, i1)).getTitle();
return true;
}
});