Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

ExpandableListItemAdapter

Niek Haarman edited this page Jun 10, 2014 · 3 revisions

Adding smooth expandable items to your ListViews is very simple:

  • Extend ExpandableListItemAdapter, implementing the getTitleView(int, View, ViewGroup) and getContentView(int, View, ViewGroup) methods.
  • (Optionally) You can provide a custom ViewGroup to serve as the 'master' View, it should contain two ViewGroups. Provide your 'master' ViewGroup layout resource id, and the two 'child' ViewGroups' resource id's in the ExpandableListItemAdapter constructor.
  • Create a new instance of your ExpandableListItemAdapter, call setAbsListView on it, and set it to your ListView!

The title View is shown when the list item is collapsed, the content View is shown together with the title View when the list item is expanded.

Example:

private static class MyExpandableListItemAdapter extends ExpandableListItemAdapter<Integer> {

	private Context mContext;

	/*
	 * This will create a new ExpandableListItemAdapter, providing a custom layout resource, 
     * and the two child ViewGroups' id's. If you don't want this, just pass either just the
     * Context, or the Context and the List<T> up to super.
	 */
	private MyExpandableListItemAdapter(Context context, List<Integer> items) {
		super(context, R.layout.activity_expandablelistitem_card, R.id.activity_expandablelistitem_card_parent, R.id.activity_expandablelistitem_card_content, items);
		mContext = context;			
	}

	@Override
	public View getTitleView(int position, View convertView, ViewGroup parent) {
		TextView tv = (TextView) convertView;
		if (tv == null) {
			tv = new TextView(mContext);
		}
		tv.setText(mContext.getString(R.string.expandorcollapsecard, getItem(position)));
		return tv;
	}

	@Override
	public View getContentView(int position, View convertView, ViewGroup parent) {
		TextView tv = (TextView) convertView;
		if (tv == null) {
			tv = new TextView(mContext);
		}
		tv.setText(mContext.getString(R.string.content, getItem(position)));
		return tv;
	}
}
Clone this wiki locally