最近在看一个项目的源码,有一个实现listview里嵌套listview的功能,实现方式是用Adapter嵌套Adapter。但是在主Adapter里,有一个函数用于更改子listview的布局高度。
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getpiderHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
显然这个函数会根据adapter中数据的个数调节listview布局的高度,那么为什么listview不会自己调节呢?
Because nested ListView does not need and should not be able to scroll
So in the code, you need to adjust the nested ListView to the height that can just display all the Children
As for the ListView itself, it does not care about its own height and whether it can display all the Children, because in terms of the original design, it is a scrollable component.
You can also read the code below to see the logic of ListView’s measure height
Take a look at how the height of ListView is obtained in MeasureSpec.UNSPECIFIED mode
Because ListView needs to reuse ConvertView