Last active
April 20, 2016 08:18
-
-
Save pranaypatel512/1993b07981a942b3f6f8507143c394ee to your computer and use it in GitHub Desktop.
set list view height dynamically
This file contains 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
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