第一步 重写 Listview 建一个新的类
public class MyListView extends ListView{
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
然后在代码中写:
/**
* 使ScrollView中的ListView可以正常显示
* ListView的Item根元素必须是LinearLayout
* @param 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.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
调用 就 ok了
本文介绍了一种解决ScrollView中ListView无法正确显示的问题的方法。通过重写ListView并调整测量过程,确保ListView能根据其子项自动调整高度。同时提供了一个静态方法来计算ListView应有的高度。
157

被折叠的 条评论
为什么被折叠?



