ScrollView嵌套ListView的問題一樣適用於gridview

如下文章轉自@安卓泡麪 java


在工做中,曾屢次碰到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


很少說,直接看失敗例子:   設計

    <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中只能放一個控件,通常都放LinearLayout,orientation屬性值爲vertical。在LinearLayout中放須要呈現的內容。ListView也在其中,ListView的高度設爲適應自身內容(wrap_content)。粗略一看,應該沒有什麼問題。可是看下面的實際效果圖:  code

       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 
*/
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滾動至頂端。若是你還在猶豫不決的話就選這個方法吧,我想我之後是隻會用這個方法了…

相關文章
相關標籤/搜索