Skip to content

Instantly share code, notes, and snippets.

@booknara
Last active March 5, 2018 02:24
Show Gist options
  • Save booknara/7091616 to your computer and use it in GitHub Desktop.
Save booknara/7091616 to your computer and use it in GitHub Desktop.
ListView Adjustment(Height) in ScrollView
package com.daeheehan.util;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* List View Utility
* Reference : http://nex-otaku-en.blogspot.com/2010/12/android-put-listview-in-scrollview.html
*
* @author Daehee Han (bookdori81@gmail.com)
* @since 10/17/2013
* @version 1.0.0
*
*/
public class ListViewUtil {
private static final String CNAME = ListViewUtil.class.getSimpleName();
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
@HuyTranVan
Copy link

Yeah, it works very good

@danielsotopino
Copy link

Nice code !

Copy link

ghost commented Jun 23, 2016

this doesn't give the right height ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment