Skip to content

Instantly share code, notes, and snippets.

@pranaypatel512
Last active April 20, 2016 08:18
Show Gist options
  • Save pranaypatel512/1993b07981a942b3f6f8507143c394ee to your computer and use it in GitHub Desktop.
Save pranaypatel512/1993b07981a942b3f6f8507143c394ee to your computer and use it in GitHub Desktop.
set list view height dynamically
package com.karconnect.app.utils;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* set list view height dynamically
*/
public class ListUtils {
public static void setDynamicHeight(ListView mListView) {
ListAdapter mListAdapter = mListView.getAdapter();
if (mListAdapter == null) {
// when adapter is null
return;
}
int height = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(mListView.getWidth(), MeasureSpec.UNSPECIFIED);
for (int i = 0; i < mListAdapter.getCount(); i++) {
View listItem = mListAdapter.getView(i, null, mListView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
height += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = mListView.getLayoutParams();
params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
mListView.setLayoutParams(params);
mListView.requestLayout();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment