關于 ScrollView 嵌套 ListView 時不能計算 ListView 高度的問題

今天遇到一個布局的問題,必須要用 ScrollView 嵌套 ListView ,但是當布局中有 TextView 并且高度是 wrap_content 的時候,就不能正確的計算 ListView 的高度,現在比較常見的有兩種做法:

  1. 在自定義 ListView 中重寫 onMeasure() 方法:
public class TextListView extends ListView {
        public TextListView(Context context) {
            super(context);
        }
        public TextListView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        public TextListView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }
}
  1. 在 ListView 設置自定義 adapter 后,計算每項 item 的高度,然后計算總的高度:
public void setListViewHeightBasedOnChildren(ListView listView) {
        // 獲取 ListView 對應的 Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount() 返回數據項的數目
            View listItem = listAdapter.getView(i, null, listView);
            //int desiredWidth= View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
            listItem.measure(0, 0); // 計算子項 View 的寬高
            totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // params.height 最后得到整個 ListView 完整顯示需要的高度
        listView.setLayoutParams(params);
}

還有什么更好的辦法可以留言說明,歡迎積極探討。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容