ScrollView嵌套ListView会使ListView无法滚动,ListView的高度无法展开。而ScrollView嵌套ListView有多种解决方案,我之前用的方法如下:
自定义一个ScrollView,自定义的ScrollView代码如下:
public class ListViewIntoScrollView extends ScrollView {
public ListViewIntoScrollView(Context context) {
super(context);
// 隐藏滚动条
this.setVerticalScrollBarEnabled(false);
}
public ListViewIntoScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
// 隐藏滚动条
this.setVerticalScrollBarEnabled(false);
}
/**
* 计算子 listview 的高度,从而能包含 listview
*
* @param listView
*/
public static void reSetListViewHeight(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
// 计算每一个 item 的高度
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
// 将每个 item 高度加起来 = listview 总高度
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
使用方法很简单,如下:
private ListViewIntoScrollView scrollView;
scrollView.reSetListViewHeight(listView);
把listview放进去就好了。
下面我来解释一下代码吧,
主要的代码在这里:
int totalHeight = 0;
// 计算每一个 item 的高度
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
// 将每个 item 高度加起来 = listview 总高度
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
我们要解决的问题是让ListView在ScrollView中可以正常的显示,不能正常显示的原因就是高度显示有问题。所以我们可以自己设定ListView的高度,这样就可以显示了
listview的高度应该是每个item的高度加上每个item中间的间距。
首先,我们得到了传来的listView,这样我们就可以通过listView获得每一个item,然后获得item的高度,把所有item高度累加起来,再加上间距(在listView中所有间距是相同的)。
这样就设置了listview的总高度了,从而解决正常显示问题。
我之前项目都是用的这种方式,但是这种方式其实并不好。我做项目的时候就碰到了展示出错的问题,这跟adapter有关,因为它太依赖于adapter了。
下面有个更好的方案,就是自定义listview,让listview自己把自己撑高。
代码如下:
public class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context) {
super(context);
}
/**
* 设置不滚动
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}