Создайте два XML-файла макета для группового и дочернего представлений соответственно -
Например, * group_layout.xml * и * child_layout.xml *
Эти макеты надуваются и используются в пользовательском ExpandableListAdapter, как показано ниже.
Вы можете настроить класс Adapter и установить для этого адаптера значение ExpandableListView.
public class SampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
ExpandableListView listView = (ExpandableListView) findViewById(R.id.listView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this, new ArrayList<String>(), new ArrayList<ArrayList<Vehicle>>());
// Set this adapter to the list view
listView.setAdapter(adapter);
}
}
Пользовательский класс адаптера может быть создан, как показано ниже:
class ExpandableListAdapter extends BaseExpandableListAdapter {
public ExpandableListAdapter(Context context, ArrayList<String> groups,
ArrayList<ArrayList<Vehicle>> children) {
this.context = context;
this.groups = groups;
this.children = children;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return children.get(groupPosition).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
// Return a child view. You can load your custom layout here.
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Vehicle vehicle = (Vehicle) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tvChild);
tv.setText(" " + vehicle.getName());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return children.get(groupPosition).size();
}
@Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
// Return a group view. You can load your custom layout here.
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
String group = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tvGroup);
tv.setText(group);
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
Надеюсь, это поможет вам.