Created
October 16, 2015 20:08
-
-
Save ajamaica/53ddf6a70adb0eb97b57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void setListViewHeightBasedOnChildren(ListView listView) | |
{ | |
ListAdapter listAdapter = listView.getAdapter(); | |
if(listAdapter == null) return; | |
if(listAdapter.getCount() <= 1) return; | |
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST); | |
int totalHeight = 0; | |
View view = null; | |
for(int i = 0; i < listAdapter.getCount(); i++) | |
{ | |
view = listAdapter.getView(i, view, listView); | |
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED); | |
totalHeight += view.getMeasuredHeight(); | |
} | |
ViewGroup.LayoutParams params = listView.getLayoutParams(); | |
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); | |
listView.setLayoutParams(params); | |
listView.requestLayout(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment