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

解決 Android 單一 Activity 內多個 ListView 只想讓主介面滾動的問題

編輯:關於 Android 程式設計

曾經遇到一個 bug:當同一個畫面裡有兩個 ListView,且各自的項目數量都超過手機螢幕高度時,列表無法完整顯示。一開始直覺以為在外層包一個 ScrollView 就能解決,但後來發現行不通——因為 ListView 本身就是一個可滾動的 ScrollView,ScrollView 巢狀 ScrollView 到底要把滾動權交給誰?結果反而兩個列表都滑不動。

查了 Stack Overflow 與相關討論後,主流解法是:禁用 ListView 自身的滾動,讓外層只保留一個 ScrollView 負責滾動。做法是動態計算所有 item 的總高度,據此固定 ListView 的高度。

/**
 * 動態設置 ListView 的高度
 * @param listView 目標列表
 */
public void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        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);
}

然而實測後發現高度還是不對。除錯後才理解:無論 item 內的 TextView 有幾行,getMeasuredHeight() 回傳的始終是固定值,因此文字若換行就無法正確計算高度。

最後採取折中方案,把 TextView 行為固定為單行並在結尾省略:

android:singleLine="true"
android:ellipsize="end"
android:layout_width="wrap_content"

如此 TextView 高度固定,總高度計算就能準確,這個 bug 也宣告解決。

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