fweigl
fweigl

Reputation: 22018

ListView with expandable Header view

I want to create a ListView with a header view that can be expanded and retractet just as in a ExpandableListView (but just the header view, all other views just be normal list items).

I'm using an ExpandableListView with a BaseExpandableListAdapter and treat all the other items in the list as groups that have no children. This is cumbersome and error-prone and has unwanted sideeffects.

I also tried using a normal ListView and a view for the header where I setVisivility(View.VISIBLE) to the expanded part of the view when the header view is clicked, but this doesn't seem to have any effect:

private View getHeaderView() {

    final View v = layoutInflater.inflate(R.layout.headertest, null);

    View v1 = v.findViewById(R.id.view1);

    final View v2 = v.findViewById(R.id.view2);

    v1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Log.d("head", "click");
            v2.setVisibility(View.VISIBLE);
            notifyDataSetChanged();

        }
    });

    return v;

}

When v1 is clicked, the visibility of v2 is not changed, although the clickListener is called. I also tried .invalidate() on all kinds of views, to no avail.

Any ideas on how to solve this one or the other way?

Upvotes: 0

Views: 576

Answers (1)

Simas
Simas

Reputation: 44118

You can do it with the expandable list view. First disable the indicators (open/close icons) on your ListView:

mExpList.setIndicator(null);

Next, your header (first group) will have to be a special type of group which has an image (an indicator) in its layout. Basically you want to have 2 types of group views:

@Override
public int getGroupTypeCount() {
    return 2;
}

@Override
public int getGroupType(int groupPosition) {
    if (groupPosition == headerPosition) {
        return 1;
    } else {
        return 0;
    }
}

You will also need to Override onGroupExpanded and onGroupCollapsed to change the image of your header (if a header was clicked of course).

Lastly you'll need to override the ListView's OnGroupClickListener:

    mExpList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (groupPosition == header) {

                // Click was not handled
                return false;
            } else {
                // Do some normal stuff with items
                // Click was handled group won't be (or tried to be) expanded
                return true;
            }
        }
    });

Also a good idea would be to override adapters getChildCount to return 0 when it's not a header.

Hope this helps. Good luck!

Upvotes: 2

Related Questions