本帖最后由 echohe 于 2014-4-9 10:13 編輯
以下文章轉(zhuǎn)自@安卓泡面
在工作中,曾多次碰到ScrollView嵌套ListView的問題,網(wǎng)上的解決方法有很多種,但是雜而不全。我試過很多種方法,它們各有利弊。 在這里我將會從使用ScrollView嵌套ListView結(jié)構(gòu)的原因、這個結(jié)構(gòu)碰到的問題、幾種解決方案和優(yōu)缺點比較,這4個方面來為大家闡述、分析、總結(jié)。 實際上不光是ListView,其他繼承自AbsListView的類也適用,包括ExpandableListView、GridView等等,為了方便說明,以下均用ListView來代表。
一、 為什么要使用ScrollView嵌套ListView的奇怪的結(jié)構(gòu)
ScrollView和ListView都是滾動結(jié)構(gòu),按理說,這兩個控件在UI上的功能是一樣的,但是看看下面這個設(shè)計:  這是天貓商城的確認(rèn)訂單的頁面,ScrollView中嵌套了ExpandableListView,ExpandableListView上面有固定的一些控件,下面也有固定的一些控件,整體又要能夠滾動。 列表數(shù)據(jù)要嵌在固定數(shù)據(jù)中間,并且作為整體一起滾動,有了這樣的設(shè)計需求,于是就有了ScrollView嵌套ListView的奇怪結(jié)構(gòu)。
二、 ScrollView、ListView嵌套結(jié)構(gòu)碰到的問題
不多說,直接看失敗例子: - <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上方數(shù)據(jù)\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下方數(shù)據(jù)\n" />
- </LinearLayout>
- </ScrollView>
ScrollView中只能放一個控件,一般都放LinearLayout,orientation屬性值為vertical。在LinearLayout中放需要呈現(xiàn)的內(nèi)容。ListView也在其中,ListView的高度設(shè)為適應(yīng)自身內(nèi)容(wrap_content)。粗略一看,應(yīng)該沒有什么問題。但是看下面的實際效果圖:
 圖中黑框的部分就是ListView,里面放了20條數(shù)據(jù),但是卻只顯示了1條。 控件的屬性設(shè)置上沒有問題,但是為什么沒有按照我的想法走呢? 看看下面這個圖:  是否有點明白了呢?原因就是scroll事件的消費處理以及ListView控件的高度設(shè)定問題。 雖然我看源碼也看了不少,但是要說出來卻不知到該怎么下手,我是大概知道原因,但是不知道怎么整理完全。求高手賜教…
三、問題解決方案
1、手動設(shè)置ListView高度 經(jīng)過測試發(fā)現(xiàn),在xml中直接指定ListView的高度,是可以解決這個問題的,但是ListView中的數(shù)據(jù)是可變的,實際高度還需要實際測量。于是手動代碼設(shè)置ListView高度的方法就誕生了。
- /**
- * 動態(tài)設(shè)置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);
- }
上面這個方法就是設(shè)定ListView的高度了,在為ListView設(shè)置了Adapter之后使用,就可以解決問題了。 但是這個方法有個兩個細(xì)節(jié)需要注意: 一是Adapter中g(shù)etView方法返回的View的必須由LinearLayout組成,因為只有LinearLayout才有measure()方法,如果使用其他的布局如RelativeLayout,在調(diào)用listItem.measure(0, 0);時就會拋異常,因為除LinearLayout外的其他布局的這個方法就是直接拋異常的,沒理由…。我最初使用的就是這個方法,但是因為子控件的頂層布局是RelativeLayout,所以一直報錯,不得不放棄這個方法。 二是需要手動把ScrollView滾動至最頂端,因為使用這個方法的話,默認(rèn)在ScrollView頂端的項是ListView,具體原因不了解,求大神解答…可以在Activity中設(shè)置:
- sv = (ScrollView) findViewById(R.id.act_solution_1_sv);
2、使用單個ListView取代ScrollView中所有內(nèi)容 這個方法是我在試了幾個方法都失敗的情況下自己琢磨出來的。 用一張圖來解釋這個方法的思想:
就是說,把整個需要放在ScrollView中的內(nèi)容,統(tǒng)統(tǒng)放在ListView中,原ListView上方的數(shù)據(jù)和下方數(shù)據(jù),都作為現(xiàn)ListView的一個itemView,和原ListView中的單條數(shù)據(jù)是平級的關(guān)系。 xml布局方面十分簡單:
- <ListView
- android:id="@+id/act_solution_2_lv"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </ListView>
一個單獨的ListView就可以了。 原ListView上方數(shù)據(jù)和下方數(shù)據(jù),都寫進(jìn)兩個xml布局文件中:
Java代碼方面,需要自定義一個Adapter,在Adapter中的getView方法中進(jìn)行position值的判斷,根據(jù)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 + "條數(shù)據(jù)");
- return convertView;
- }
在Activty中,只需要直接為ListView設(shè)置自定義的Adapter就行了。
- lv = (ListView) findViewById(R.id.act_solution_2_lv);
- adapter = new AdapterForListView2(this);
- lv.setAdapter(adapter);
3、使用LinearLayout取代ListView 既然ListView不能適應(yīng)ScrollView,那就換一個可以適應(yīng)ScrollView的控件,干嘛非要吊死在ListView這一棵樹上呢?而LinearLayout是最好的選擇。但如果我仍想繼續(xù)使用已經(jīng)定義好的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);
4、自定義可適應(yīng)ScrollView的ListView 這個方法和上面的方法是異曲同工,方法3是自定義了LinearLayout以取代ListView的功能,但如果我脾氣就是倔,就是要用ListView怎么辦?那就只好自定義一個類繼承自ListView,通過重寫其onMeasure方法,達(dá)到對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
- /**
- * 重寫該方法,達(dá)到使ListView適應(yīng)ScrollView的效果
- */
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
- MeasureSpec.AT_MOST);
- super.onMeasure(widthMeasureSpec, expandSpec);
- }
- }
三個構(gòu)造方法完全不用動,只要重寫onMeasure方法,需要改動的地方比起方法3少了不是一點半點… 在xml布局中和Activty中使用的ListView改成這個自定義ListView就行了。代碼就省了吧… 這個方法和方法1有一個同樣的毛病,就是默認(rèn)顯示的首項是ListView,需要手動把ScrollView滾動至最頂端。
- sv = (ScrollView) findViewById(R.id.act_solution_4_sv);
- sv.smoothScrollTo(0, 0);
5、設(shè)置ScrollView的屬性,使ListView能夠成功嵌套(無法達(dá)到預(yù)定效果) 這個方法是我在寫Demo的時候找到的,第一反應(yīng)是有這個方法我還寫這個Demo干嘛,只要在布局文件中添加一個屬性就搞定了。不過結(jié)果確實是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">
設(shè)置fillViewport的屬性為true即可。簡單吧? 但是不能滾動這個致命的問題我卻不知道該怎么解決了,繼續(xù)求大神解答…
四、幾種種方法的優(yōu)缺點比較
上面一共給出了4中親測可用的方法,各自有使用條件,復(fù)雜程度也各不相同。 下面我來從幾個方面來分析幾種方法的優(yōu)勢和劣勢。 方法1的優(yōu)點是不用對使用的控件做任何修改,只需要使用一個現(xiàn)成的方法就好了,而最大的限制是ListView的item只能由LinearLayout這一個布局組成,對于一些復(fù)雜的布局就不適用了。如果你的工程急需解決這個問題,而且滿足方法的使用條件,即ListView的item布局簡單,完全有LinearLayout組成,你就只需要把setListViewHeightBasedOnChildren方法拿過去就行了。 方法2的優(yōu)點是布局文件設(shè)計簡單、Activity中的代碼也很少,而缺點卻是自定義Adapter變得十分復(fù)雜,而且執(zhí)行效率會變低,因為findViewById是十分費時的操作,而使用ViewHolder結(jié)構(gòu)可以解決費時的問題(有興趣的童鞋可以去搜一艘ViewHolder結(jié)構(gòu)),然而使用了方法2的話,會破壞這種結(jié)構(gòu)。如果你的工程設(shè)計上偏簡單,ListView子項相對少、ListView上下方數(shù)據(jù)少、子項間交互少的話,可以嘗試一下。 方法3的優(yōu)點是完全解決了ScrollView嵌套ListView的問題,同時代碼較少,你甚至可以直接使用LinearLayout,而在Activity中手動為LinearLayout添加子項控件,不過需要注意的是,在添加前需要調(diào)用其removeAllViews的方法,否則可能會出現(xiàn)預(yù)想不到的事情,那時你會想念天國的ListView的。缺點不是很明顯,但還是有兩個:一是使用的不是系統(tǒng)控件,不能在xml布局的Graphical Layout視圖中直接看到效果;二是不能向ListView那樣可以使用ViewHolder結(jié)構(gòu),在加載大量子項時會費很多時間在findViewById中。如果你的列表數(shù)據(jù)比較少的話,不妨試試這個方法,除了不能使用ViewHolder結(jié)構(gòu),使用方法幾乎和ListView一樣。 方法4…比方法3更簡單,代碼更少,同時保留了ListView原有的所有方法,包括notifyDataSetChanged方法,相比其他方法是最趨近于完美的方法,只是需要在Activity中設(shè)定ScrollView滾動至頂端。如果你還在猶豫不決的話就選這個方法吧,我想我以后是只會用這個方法了…
|