Android Tidbits 6/22/2011: Hiding Header Views

June 22, 2011 Joe Moore

Android ListView#addHeaderView and ListView#addFooterView methods are strange: you have to add the header and footer Views before you set the ListView‘s adapter so the ListView can take the headers and footers into consideration — you get an exception otherwise. Here we add a ProgressBar (spinner) as the headerView:

// spinner is a ProgressBar

We’d like to be able to show and hide that spinner at will, but removing it outright is dangerous because we’d never be able to add it again without destroying the ListView — remember, we can’t addHeaderView after we’ve it’s adapter:

listView.removeHeaderView(spinner); //dangerous!

So let’s hide it! Turns out that’s hard, too. Just hiding the spinner view itself results in an empty, but still visible, header area.

Now try to hide the spinner:


Result: header area still visible with an ugly space:

The solution is to put the progress bar in a LinearLayout that wraps it’s content, and hiding the content. That way the wrapping LinearLayout will collapse when its content is hidden, resulting in a headerView that is technically still present, but 0dip high:

    <!-- simplified -->

Then, set the layout as the header:

spinnerLayout = getLayoutInflater().inflate(R.layout.header_view_spinner, null);

And when we need to hide it, hide the layout’s content, not the layout:


Now the header disappears from view. No more ugly space at the top!

About the Author


More Content by Joe Moore
auto_tagger and alternate tag refs
auto_tagger and alternate tag refs

A recent addition to Jeff Dean's auto_tagger is the ability to use an alternate tag ref type instead of sta...

Android Tidbits 6/21/2011: Unregister? Nah!
Android Tidbits 6/21/2011: Unregister? Nah!

C2DM Unregister Issues It turns out when you follow the client-side C2DM unregistration process, this does...

Enter curious. Exit smarter.

Register Now