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 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;