转载请注明:[noyet12的博客](http://blog.csdn.net/u012975705)
博客原址:http://blog.csdn.net/u012975705/article/details/50034847
1、在ScrollView或ListView等滑动控件中嵌套ListView时,往往会导致ListView显示不完整,只显示一条数据,想使ListView显示完整可以通过重写ListView的onMeasure方法来解决:
package com.plusub.rentlandapp.view.version2;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* package: com.plusub.rentlandapp.view.version2
* Created by noyet on 2015/11/9.
*/
public class CustomListView extends ListView {
public CustomListView(Context context) {
super(context);
}
public CustomListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
2、除此外还有一种解决方法:根据ListView子项重置其高度。
java代码:
/**
* 重新计算ListView的高度,解决ScrollView和ListView两个View都有滚动的效果,在嵌套使用时起冲突的问题
* @param listView
*/
public void setListViewHeight(ListView listView) {
// 获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); // 计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
在设置LIstView的Adapter填充数据后调用此方法便可。
但是要注意的是,子ListView的每个Item必须是LinearLayout,不能是其他的,因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常。