我四处寻找这个问题的解决方案,我能找到的唯一答案似乎是“don't put a ListView into a ScrollView”。不过,我还没有看到任何真正的解释。我似乎能找到的唯一原因是谷歌认为你不应该这样做。好吧,我做到了,所以我做到了。
所以问题是,如何将 ListView 放入 ScrollView 而不使其折叠到最小高度?
这是我的解决方案。我对 Android 平台还很陌生,我敢肯定这有点骇人听闻,尤其是在关于直接调用 .measure 并设置 LayoutParams.height
的部分。属性(property)直接,但它的作品。
您只需调用Utility.setListViewHeightBasedOnChildren(yourListView)
并且它将调整大小以完全适应其项目的高度。
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup) {
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
关于android - 如何在不折叠的情况下将 ListView 放入 ScrollView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3495890/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |