I have a rather complex ListView, with variable list item heights. Under certain conditions, I need to display an additional view in a list item, which is hidden by default
How are you inflating your rows?
If you are not using it right now, try using LayoutInflater#inflate(layoutId, parent, false)
(where parent
is the AdapterView
supplied to getView()
or newView()
):
v = getLayoutInflater().inflate(R.layout.list_item, parent, false);
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();
}
}
If you're using a custom View
in as the list item that is resizing, then you can take from PeBek's answer and do this when you construct the View
addOnLayoutChangeListener(
new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View _, int __, int ___, int ____, int bottom, int _____, int ______,
int _______, int old_bottom) {
final ListView list_view = (ListView) getParent();
final ViewGroup.LayoutParams params = list_view.getLayoutParams();
params.height += bottom - old_bottom;
list_view.setLayoutParams(params);
list_view.requestLayout();
}
});
When the View
gets resized this callback method will me run and it updates the ListView
height to include the change in height (delta bottom). The other values, if they prove useful for you are view
(reference to the view), left
, top
, right
, bottom
, old_left
, old_top
, old_right
, old_bottom
. It works for expanding and collapsing the view.
API 11 is required for OnLayoutChangeListener
, don't know if there's a backward compatible way to do so.