Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中 ListView 與 ScrollView 的協作與優化

編輯:關於 Android 程式設計

一、ListView 該如何與 ScrollView 共存?

有些場景下,我們需要在 ListView 外層再套一層 ScrollView,代碼大致如下:

<ScrollView
    android:id="@+id/scrollview"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
    <ListView
        android:id="@+id/listview"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
    </ListView>
</ScrollView>

稍微有點經驗的人都知道,這樣寫會出問題——「ListView 只顯示一兩條,展不開」。原因很簡單:ListView 處在 ScrollView 內部時,無法正確計算自身高度,於是只按一行來渲染。

針對這個問題,目前常見的解法有以下幾種:

1. 方法一:自定義 ListView,重寫 onMeasure()

核心思路是在測量時,把高度規格放寬為一個足夠大的 AT_MOST 值,讓 ListView 得以完整鋪開:

public class WrapperListView extends ListView {
    public WrapperListView(Context context) { super(context); }
    public WrapperListView(Context context, AttributeSet attrs) { super(context, attrs); }
    public WrapperListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public WrapperListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    /** 重寫此方法,讓 ListView 能夠適應 ScrollView */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

布局中把原本的 ListView 替換成這個自定義控件即可,Activity 裡正常 setAdapter 就能顯示全部條目。

2. 方法二:動態計算並設置 ListView 的高度

這種方式不必自定義 ListView,只需在 setAdapter 之後調用下面的方法,手動把每個子項測一遍並累加高度:

public void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        return;
    }
    int totalHeight = 0;
    for (int i = 0, len = listAdapter.getCount(); i < len; 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 外再套一層 LinearLayout,否則偶爾會失效:

<ScrollView
    android:id="@+id/scrollview"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">
        <ListView
            android:id="@+id/listview"
            android:layout_height="match_parent"
            android:layout_width="fill_parent"
            android:dividerHeight="0.0dip"
            android:fadingEdge="vertical" />
    </LinearLayout>
</ScrollView>
3. 方法三:直接在 XML 中寫死 ListView 的高度

這種方式確實能改變 ListView 的高度,但問題也很明顯:列表數據是動態變化的,除非你能精確預知所有數據下的合適高度,否則這法子形同雞肋。

4. 方法四:乾脆不嵌套

很多時候,我們完全可以避免 ScrollView 套 ListView。比如用 ListView 的 addHeaderView() 把頭部內容做成 Header,或者借助布局特性達到同樣效果。具體怎麼取捨,需要在實戰中慢慢摸索、慢慢總結。

至此,「ListView 如何與 ScrollView 共存」這個問題就算說清楚了。

二、ListView 該如何優化?

關於 ListView 優化,面試過的人應該都不陌生,網上也能搜到一大堆。這裡簡單提幾個核心要點:

1)convertView 復用:先對 convertView 判空,不為空就重複使用,為空才初始化,從而減少大量不必要的 View 創建。

2)引入 ViewHolder:把列表項中的所有子控件封裝進 ViewHolder,並將 convertView 的 tag 設為該 ViewHolder,復用時直接從 tag 取出,避免重複 findViewById。

3)數據量大時採用分頁加載與圖片異步加載。

一些常見拓展問題

1. 打開套有 ListView 的 ScrollView 頁面,默認起始位置不在頂部?

兩種解法:其一,不讓內層 ListView 獲取焦點,listView.setFocusable(false)(注意在 XML 裡設置 android:focusable="false" 往往不生效);其二,myScrollView.smoothScrollTo(0, 0)。

2. 上拉加載與下拉刷新怎麼實現?

實現 OnScrollListener 接口,重寫 onScrollStateChanged 與 onScroll。在 onScroll 中判斷是否滑到底部、是否還有新數據,有則 addFooterView 並向 adapter 追加數據後 notifyDataSetChanged;沒有則移除自定義的 mFooterView。而 onScrollStateChanged 則可用來判斷是否滾到最後一行且已停止滾動,再觸發加載。

3. ListView 失去焦點怎麼辦?

在列表項的子布局中加上 android:descendantFocusability="blocksDescendants",即可阻止子控件搶走焦點。

4. ListView 圖片異步加載的思路?

1. 先從內存緩存中取圖顯示;
2. 取不到就從 SD 卡讀取(讀 SD 卡要放在子線程,否則快速滑屏時會卡頓);
3. 都取不到就從網絡下載,保存到 SD 卡的同時寫入內存並顯示。

5. ListView 裡放 Button 就點不動了?

原因是 Button 搶占了列表項的焦點,只要把 Button 的 focusable 設為 false 即可。

6. 如何自定義 Adapter?

繼承 BaseAdapter 並實現其抽象方法。ListView 繪製時會先調用 getCount() 拿到列表長度,再逐一調用 getView() 繪製每一行——若 getCount() 返回 0 則列表不顯示,返回 1 則只顯示一行。getView() 有三個參數:position 表示第幾行,convertView 是從布局 inflate 出來的視圖,parent 是父容器。我們用 LayoutInflater 把布局文件轉成 View,再 findViewById 取出各控件並綁定數據即可。若控件需要響應點擊,記得註冊監聽器。

7. ListView 分頁加載的步驟?

常見兩種做法:一是在底部放一個「加載更多」按鈕,點擊後顯示進度條、異步加載數據、刷新 adapter;二是監聽滑動事件,當滑到底部並停止時自動加載。兩者關鍵都在於合適地追加數據並調用 notifyDataSetChanged 刷新。

8. ViewHolder 內部類一定要聲明成 static 嗎?

這並非 Android 的優化要求,而是 Java 提倡的做法。若非靜態成員類不需要訪問外部實例,就應始終加上 static 修飾符。因為非靜態成員類的實例會隱含一個指向外部對象的引用,保存這份引用既耗時又佔空間,還會導致外部類在該被回收時仍被牽連。此外,非靜態成員類的實例必須依附於一個外部實例才能創建。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved