android-如何强制listView的高度为大小,以便每一行都可见?
作者:互联网
我嵌套了listView.如何强制将listView的高度设置为大小,以使每一行都可见?
ListView嵌套在ScrollView内,所以滚动不适用于ListView,因此我需要使所有项目在嵌套在ScrollView的ListView内可见(上面还有下面的东西).
解决方法:
计算listView的高度
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
将listview对象传递给此方法.
setListViewHeightBasedOnChildren(listView)
标签:android-widget,android 来源: https://codeday.me/bug/20191101/1985109.html