I understand that putting a ListView inside a ScrollView is not recommmender. But I must use a ListView, simply because I'm using an adapter and various other methods.
I have used this code, which I found on StackOverflow and it shows me the majority of my list. However, in portrait mode some items are cut off from the bottom and in landscape mode the same.
How can this be rectified? To clarify, I've got a ScrollView containing a LinearLayout containing some elements and my ListView in my XML.
In addition, if I go to a new activity, then return I can briefly see the scroll bars for listview show up and disappear. How can this be rectified too?
public static boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
// Get total height of all items.
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(numberOfItems - 1);
// Set list height.
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
return true;
} else {
return false;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…