ListView header ignores layout_height

I inflate this view and add it to my ListView as a title. I'm trying to make it 500dp high (hard code, for the sake of this example)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@drawable/repeat_background" android:layout_height="500dp"> <ImageView android:id="@+id/filter_menu" android:src="@drawable/ic_sort" android:layout_gravity="center_vertical" android:padding="8dp" android:layout_weight="0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showPopup"/> </LinearLayout> 

ListView does not respect the authority of its title and wraps it in its content. Can someone explain what is happening?

+7
android listview layout
source share
1 answer

The key to understanding what is happening is to find out how the ListView headers and footers are implemented. This is a trick: when you add the first header or footer to your ListView, your ListAdapter is wrapped in the HeaderViewListAdapter line (happens on line 270 of the ListView.java list ). HeaderListViewAdapter is a list adapter that adjusts the count and position values โ€‹โ€‹to include headers and footers; Headers and footers become regular list items that the system runs for you.

If you look at line 207 in HeaderListViewAdapter.java , you will see that the getView implementation ignores the parent view when adding a header or mLayoutParams its mLayoutParams not to be initialized from XML (actually cannot point to the source code, only what I discovered over time).

If you then follow the getView calls for bits, the last line 2237 from AbsListView.java and follow the obtainView calls for bits and find LayoutParams (this is what I just did), you get to line 1182 ListView.java . Here you can see that if the layout parameters are null when the child view is measured, it calls generateDefaultLayoutParams() , which is implemented on line 6065 of AbsListView.java :

 @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); } 

... and where your WRAP_CONTENT comes WRAP_CONTENT .

To make it easy, just wrap <LinearLayout/> your XML inside <FrameLayout/> . Store 500dp in LinearLayout and create a FrameLayout with the height of the layout WRAP_CONTENT (which will be ignored anyway).

+12
source share

All Articles