在list信息庞大的时候,或者是想为这些信息分组的时候,你可能需要用到这中listview来美化界面。他的效果如同我们熟知的QQ的联系人界面,可以为你的联系人分组,点击组名之后会显示出该组所有的联系人,再次点击隐藏该组联系人
private List<String> groupArray;
private List<List<String>> childArray;
public class ExpandableAdapter extends BaseExpandableListAdapter {
Activity activity;
public ExpandableAdapter(Activity a) {
activity = a;
}
public Object getChild(int groupPosition, int childPosition) {
return childArray.get(groupPosition).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return childArray.get(groupPosition).size();
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
String string = childArray.get(groupPosition).get(childPosition);
return getGenericView(string);
}
// group method stub
public Object getGroup(int groupPosition) {
return groupArray.get(groupPosition);
}
public int getGroupCount() {
return groupArray.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String string = groupArray.get(groupPosition);
return getGenericView(string);
}
// View stub to create Group/Children 's View
public TextView getGenericView(String string) {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 64);
TextView text = new TextView(activity);
text.setLayoutParams(layoutParams);
// Center the text vertically
text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
text.setPadding(36, 0, 0, 0);
text.setText(string);
return text;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
@Override
protected void onCreate(Bundle saveInstanceBundle) {
super.onCreate(saveInstanceBundle);
setContentView(R.layout.fragment_main);
groupArray = new ArrayList<String>();
childArray = new ArrayList<List<String>>();
groupArray.add("第一行");
groupArray.add("第二行");
List<String> tempArray = new ArrayList<String>();
tempArray.add("第一条");
tempArray.add("第二条");
tempArray.add("第三条");
for (int index = 0; index < groupArray.size(); ++index) {
childArray.add(tempArray);
}
ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
expandableListView.setAdapter(new ExpandableAdapter(MainActivity.this));
}
只需要在xml文件中有下面布局即可:
<ExpandableListView
android:id="@+id/expandableListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ExpandableListView>