Is there a way to have a ListView with the with equal to the longest row? Setting wrap_content for the ListView \'s width has no effect. The ListView covers the whole screen
Sometimes, you know there will always be a limited number of items, maybe 5, maybe 40. In those times you still want to use a ListView and you still want to wrap content.
For those times there is this method:
/**
* Computes the widest view in an adapter, best used when you need to wrap_content on a ListView, please be careful
* and don't use it on an adapter that is extremely numerous in items or it will take a long time.
*
* @param context Some context
* @param adapter The adapter to process
* @return The pixel width of the widest View
*/
public static int getWidestView(Context context, Adapter adapter) {
int maxWidth = 0;
View view = null;
FrameLayout fakeParent = new FrameLayout(context);
for (int i=0, count=adapter.getCount(); i<count; i++) {
view = adapter.getView(i, view, fakeParent);
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = view.getMeasuredWidth();
if (width > maxWidth) {
maxWidth = width;
}
}
return maxWidth;
}
Use it like so (notice I added some extra space to the width just in case):
listView.getLayoutParams().width = getWidestView(mContext, adapter)*1.05;
Is there a way to have a ListView with the with equal to the longest row?
No, in part because we have no way to know what the longest row is.
Let's say that you attach a ListAdapter
to the ListView
, where getCount()
on the ListAdapter
returns a value of 1,234,567
. To determine the width of the longest row, we would have to create each row and examine its width. This would take hours, and the user will not be happy during those hours.