Why do ListView items not grow to wrap their content?
Try this: http://www.java2s.com/Code/Android/UI/setListViewHeightBasedOnChildren.htm
public class Utils {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
I managed to fix this, but I don't understand why.
As I mentioned, I had set the layout_height
of the list item layout to wrap_content
(since fill_parent
is meaningless here, considering that a ListView is indefinitely tall).
However, I had set the layout_height
of all views inside that layout to fill_parent
. The problem disappeared when setting them to wrap_content
instead.
This raises two other questions:
1) What are the semantics of a view asking to fill_parent
, when the parent wraps_content
? Which size request takes precedence?
2) How would I ever make a view fill a list item if fill_parent
apparently doesn't work?
Thanks for your input guys.