tags:

views:

44

answers:

1

Hi!

I need to define the structure of ExpandableListView in xml file manually. Is there any guide or example of doing this?

Thanks

+2  A: 

Hello, I run into this two days ago. Here's my solution:

First extend ExpandableListActivity and override the onCreate() method like this:

public class ExpandableExample extends ExpandableListActivity {
    @Override
    public void onCreate() {
        super.onCreate(savedInstanceState);
        setListAdapter(new BaseExpandableListAdapterExample());
    }
}

The definition of BaseExpanableListAdapterExample is (inner class of ExpandableExample):

protected class BaseExpandableListAdapterExample extends BaseExpandableListAdapter {
}

Then you need to implement getChildView y getGroupView. What I did was:

public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    View groupRow = getLayoutInflater().inflate(R.layout.group_row, null);
    TextView textView = (TextView) groupRow.findViewById(R.id.text_group);
    textView.setText(getGroup(groupPosition).toString());
    return groupRow;
}

public View getChildView(int groupPosition, int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {
    View childRow = getLayoutInflater().inflate(R.layout.child_row, null);
    TextView textView = (TextView) childRow.findViewById(R.id.text_child);
    textView.setText(getChild(groupPosition, childPosition).toString());
    return childRow;
}

Then you need to define both group_row.xml and child_row.xml under /res/layout/ directory. For example, my group_row.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/text_element"
        android:layout_width="fill_parent"
        android:layout_height="48dip"
        android:textSize="20sp"
        android:textColor="#fff"
        android:layout_marginLeft="48dip"
        android:gravity="center_vertical" />
</RelativeLayout>

Hope it helps. Comment if you have any question.

licorna
Thanks very much. That's great but I need to retrieve content from XML as well. Maybe I should consider parsing my XML manually to data structures suitable to use in SimpleExpandableListAdapter?
Aleksander O
Aleksander, look at http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.html for an example on how to populate an ExpandableListView manually, without using an Adapter.
licorna
Are you sure that the link is correct? That code does use a provider. It simply defines it's own one :)But creating own provider which will parse XML data seems to look like a solution.
Aleksander O