解决ScrollView嵌套ListView问题

解决ScrollView嵌套ListView问题

在学习开发中,曾多次碰到ScrollView嵌套ListView的问题,确认订单的页面,ScrollView中嵌套了ExpandableListView,ExpandableListView上面有固定的一些控件,下面也有固定的一些控件,整体又要能够滚动。 列表数据要嵌在固定数据中间,并且作为整体一起滚动。但是网上查到的解决办法好多无法真正解决,这里介绍一种亲测有效的办法。

先看一个例子

<ScrollView
android:id="@+id/act_solution_1_sv"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="\nListView上方数据\n" />
<ListView
android:id="@+id/act_solution_1_lv"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="\nListView下方数据\n" />
</LinearLayout>
</ScrollView><ScrollView
android:id="@+id/act_solution_1_sv"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="\nListView上方数据\n" />
<ListView
android:id="@+id/act_solution_1_lv"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="\nListView下方数据\n" />
</LinearLayout>
</ScrollView>

接着在ListView中放里面放了很多条数据,但是却只显示了1条。控件的属性设置上看没有什么问题,为什么不能像预期的那样?原因就是scroll事件的消费处理以及ListView控件的高度设定问题。

解决方案:手动设置ListView高度

经过测试发现,在xml中直接指定ListView的高度,是可以解决这个问题的,但是ListView中的数据是可变的,实际高度还需要实际测量。于是手动代码设置ListView高度的方法就诞生了。

/**
* 动态设置ListView的高度
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
if(listView == null) return;
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
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);
}

上面这个方法就是设定ListView的高度了,在为ListView设置了Adapter之后使用,就可以解决问题了。
但是这个方法有个两个细节需要注意:
一是Adapter中getView方法返回的View的必须由LinearLayout组成,因为只有LinearLayout才有measure()方法,如果使用其他的布局如RelativeLayout,在调用listItem.measure(0, 0);时就会抛异常,因为除LinearLayout外的其他布局的这个方法就是直接抛异常的,没理由…。我最初使用的就是这个方法,但是因为子控件的顶层布局是RelativeLayout,所以一直报错,不得不放弃这个方法。
二是需要手动把ScrollView滚动至最顶端,因为使用这个方法的话,默认在ScrollView顶端的项是ListView,具体原因不了解可以在Activity中设置:
sv = (ScrollView) findViewById(R.id.act_solution_1_sv);

作者:王雨扬
原文链接:点击这里

猜你喜欢

转载自blog.csdn.net/fjnu_se/article/details/80768424