四种方案解决ScrollView嵌套ListView问题

在工做中,曾屡次碰到ScrollView嵌套ListView的问题,网上的解决方法有不少种,可是杂而不全。我试过不少种方法,它们各有利弊。android

在这里我将会从使用ScrollView嵌套ListView结构的缘由、这个结构碰到的问题、几种解决方案和优缺点比较,这4个方面来为你们阐述、分析、总结。ide

实际上不光是ListView,其余继承自AbsListView的类也适用,包括ExpandableListView、GridView等等,为了方便说明,如下均用ListView来表明。布局


1、 为何要使用ScrollView嵌套ListView的奇怪的结构        测试


ScrollView和ListView都是滚动结构,按理说,这两个控件在UI上的功能是同样的,可是看看下面这个设计:this

141.png

这是天猫商城的确认订单的页面,ScrollView中嵌套了ExpandableListView,ExpandableListView上面有固定的一些控件,下面也有固定的一些控件,总体又要可以滚动。    列表数据要嵌在固定数据中间,而且做为总体一块儿滚动,有了这样的设计需求,因而就有了ScrollView嵌套ListView的奇怪结构。spa



2、 ScrollView、ListView嵌套结构碰到的问题   .net


很少说,直接看失败例子:   设计


  •     <ScrollVieworm

  •     android:id="@+id/act_solution_1_sv"xml

  •     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中只能放一个控件,通常都放LinearLayout,orientation属性值为vertical。在LinearLayout中放须要呈现的内容。ListView也在其中,ListView的高度设为适应自身内容(wrap_content)。粗略一看,应该没有什么问题。可是看下面的实际效果图:
  

       142.png

    图中黑框的部分就是ListView,里面放了20条数据,可是却只显示了1条。
    控件的属性设置上没有问题,可是为何没有按照个人想法走呢?
    看看下面这个图:
    143.png


    是否有点明白了呢?缘由就是scroll事件的消费处理以及ListView控件的高度设定问题。
    虽然我看源码也看了很多,可是要说出来殊不知到该怎么下手,我是大概知道缘由,可是不知道怎么整理彻底。求高手赐教…




3、问题解决方案

一、手动设置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);



二、使用单个ListView取代ScrollView中全部内容
    这个方法是我在试了几个方法都失败的状况下本身琢磨出来的。
    用一张图来解释这个方法的思想:
    
144.png 


    就是说,把整个须要放在ScrollView中的内容,通通放在ListView中,原ListView上方的数据和下方数据,都做为现ListView的一个itemView,和原ListView中的单条数据是平级的关系。
    xml布局方面十分简单:

  • <ListView

  •     android:id="@+id/act_solution_2_lv"

  •     android:layout_width="fill_parent"

  •     android:layout_height="wrap_content">


  • </ListView>





   一个单独的ListView就能够了。
    原ListView上方数据和下方数据,都写进两个xml布局文件中:

     
    Java代码方面,须要自定义一个Adapter,在Adapter中的getView方法中进行position值的判断,根据position值来决定inflate哪一个布局:

  • public View getView(int position, View convertView, ViewGroup parent) {

  •             //列表第一项

  •     if(position == 0){

  •        convertView = inflater.inflate(R.layout.item_solution2_top, null);

  •         return convertView;

  •     }

  •             //列表最后一项

  •     else if(position == 21){

  •         convertView = inflater.inflate(R.layout.item_solution2_bottom, null);

  •         return convertView;

  •     }


  •             //普通列表项

  •     ViewHolder h = null;

  •     if(convertView == null || convertView.getTag() == null){

  •         convertView = inflater.inflate(R.layout.item_listview_data, null);

  •         h = new ViewHolder();

  •         h.tv = (TextView) convertView.findViewById(R.id.item_listview_data_tv);

  •         convertView.setTag(h);

  •     }else{

  •         h = (ViewHolder) convertView.getTag();

  •     }


  •     h.tv.setText("第"+ position + "条数据");


  •     return convertView;

  • }




    在Activty中,只须要直接为ListView设置自定义的Adapter就好了。
  • lv = (ListView) findViewById(R.id.act_solution_2_lv);

  • adapter = new AdapterForListView2(this);

  • lv.setAdapter(adapter);





三、使用LinearLayout取代ListView
    既然ListView不能适应ScrollView,那就换一个能够适应ScrollView的控件,干吗非要吊死在ListView这一棵树上呢?而LinearLayout是最好的选择。但若是我仍想继续使用已经定义好的Adater呢?咱们只须要自定义一个类继承自LinearLayout,为其加上对BaseAdapter的适配。
  • import android.content.Context;

  • import android.util.AttributeSet;

  • import android.util.Log;

  • import android.view.View;

  • import android.widget.BaseAdapter;

  • import android.widget.LinearLayout;


  • /**

  • * 取代ListView的LinearLayout,使之可以成功嵌套在ScrollView中

  • * @author terry_龙

  • */

  • public class LinearLayoutForListView extends LinearLayout {


  •     private BaseAdapter adapter;

  •     private OnClickListener onClickListener = null;


  •     /**

  •      * 绑定布局

  •      */

  •     public void bindLinearLayout() {

  •         int count = adapter.getCount();

  •         this.removeAllViews();

  •         for (int i = 0; i < count; i++) {

  •             View v = adapter.getView(i, null, null);


  •             v.setOnClickListener(this.onClickListener);

  •             addView(v, i);

  •         }

  •        Log.v("countTAG", "" + count);

  •     }


  •     public LinearLayoutForListView(Context context) {

  •         super(context);



    上面的代码拷贝保存为LinearLayoutForListView.class,或者直接拷贝Demo中的这个类在本身的工程里。咱们只须要把原来xml布局文件中的ListView替换为这个类就好了:
  • <pm.nestificationbetweenscrollviewandabslistview.mywidgets.LinearLayoutForListView

  •     android:id="@+id/act_solution_3_mylinearlayout"

  •     android:layout_width="fill_parent"

  •     android:layout_height="wrap_content"

  •     android:orientation="vertical" >

  • </pm.nestificationbetweenscrollviewandabslistview.mywidgets.LinearLayoutForListView>




    在Activity中也把ListView改为LinearLayoutForListView,就能成功运行了。
  • mylinearlayout = (LinearLayoutForListView) findViewById(R.id.act_solution_3_mylinearlayout);

  • adapter = new AdapterForListView(this);

  • mylinearlayout.setAdapter(adapter);






四、自定义可适应ScrollView的ListView
    这个方法和上面的方法是殊途同归,方法3是自定义了LinearLayout以取代ListView的功能,但若是我脾气就是倔,就是要用ListView怎么办?那就只好自定义一个类继承自ListView,经过重写其onMeasure方法,达到对ScrollView适配的效果。
    下面是继承了ListView的自定义类:

  • import android.content.Context;

  • import android.util.AttributeSet;

  • import android.widget.ListView;


  • public class ListViewForScrollView extends ListView {

  •     public ListViewForScrollView(Context context) {

  •         super(context);

  •     }


  •     public ListViewForScrollView(Context context, AttributeSet attrs) {

  •         super(context, attrs);

  •     }


  •     public ListViewForScrollView(Context context, AttributeSet attrs,

  •         int defStyle) {

  •         super(context, attrs, defStyle);

  •     }


  •     @Override

  •     /**

  •      * 重写该方法,达到使ListView适应ScrollView的效果

  •      */

  •     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  •         int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,

  •         MeasureSpec.AT_MOST);

  •         super.onMeasure(widthMeasureSpec, expandSpec);

  •     }

  • }




    三个构造方法彻底不用动,只要重写onMeasure方法,须要改动的地方比起方法3少了不是一点半点…
    在xml布局中和Activty中使用的ListView改为这个自定义ListView就好了。代码就省了吧…
    这个方法和方法1有一个一样的毛病,就是默认显示的首项是ListView,须要手动把ScrollView滚动至最顶端。
  • sv = (ScrollView) findViewById(R.id.act_solution_4_sv);

  • sv.smoothScrollTo(0, 0);





五、设置ScrollView的属性,使ListView可以成功嵌套(没法达到预约效果)
    这个方法是我在写Demo的时候找到的,第一反应是有这个方法我还写这个Demo干吗,只要在布局文件中添加一个属性就搞定了。不过结果确实是ListView的大小把ScrollView的剩余部分填满了,但却不能滚动,真是个致命的问题…
    不废话了,布局文件中:
  • <ScrollView

  •     android:id="@+id/act_solution_5_sv"

  •     android:layout_width="fill_parent"

  •     android:layout_height="fill_parent"

  •     android:layout_below="@+id/act_solution_5_vg_top"

  •     android:fillViewport="true">




    设置fillViewport的属性为true便可。简单吧?
    可是不能滚动这个致命的问题我殊不知道该怎么解决了,继续求大神解答…


4、几种种方法的优缺点比较

    上面一共给出了4中亲测可用的方法,各自有使用条件,复杂程度也各不相同。    下面我来从几个方面来分析几种方法的优点和劣势。    方法1的优势是不用对使用的控件作任何修改,只须要使用一个现成的方法就行了,而最大的限制是ListView的item只能由LinearLayout这一个布局组成,对于一些复杂的布局就不适用了。若是你的工程急需解决这个问题,并且知足方法的使用条件,即ListView的item布局简单,彻底有LinearLayout组成,你就只须要把setListViewHeightBasedOnChildren方法拿过去就好了。    方法2的优势是布局文件设计简单、Activity中的代码也不多,而缺点倒是自定义Adapter变得十分复杂,并且执行效率会变低,由于findViewById是十分费时的操做,而使用ViewHolder结构能够解决费时的问题(有兴趣的童鞋能够去搜一艘ViewHolder结构),然而使用了方法2的话,会破坏这种结构。若是你的工程设计上偏简单,ListView子项相对少、ListView上下方数据少、子项间交互少的话,能够尝试一下。    方法3的优势是彻底解决了ScrollView嵌套ListView的问题,同时代码较少,你甚至能够直接使用LinearLayout,而在Activity中手动为LinearLayout添加子项控件,不过须要注意的是,在添加前须要调用其removeAllViews的方法,不然可能会出现预想不到的事情,那时你会想念天国的ListView的。缺点不是很明显,但仍是有两个:一是使用的不是系统控件,不能在xml布局的Graphical Layout视图中直接看到效果;二是不能向ListView那样可使用ViewHolder结构,在加载大量子项时会费不少时间在findViewById中。若是你的列表数据比较少的话,不妨试试这个方法,除了不能使用ViewHolder结构,使用方法几乎和ListView同样。    方法4…比方法3更简单,代码更少,同时保留了ListView原有的全部方法,包括notifyDataSetChanged方法,相比其余方法是最趋近于完美的方法,只是须要在Activity中设定ScrollView滚动至顶端。若是你还在犹豫不决的话就选这个方法吧,我想我之后是只会用这个方法了…

相关文章
相关标签/搜索