解決listview嵌套時的高度問題

/**
     * 只要在設置ListView的Adapter後調用此靜態方法即可讓ListView正確的顯示
     * 在其父ListView的ListItem中。但是要注意的是,子ListView的每個Item必須是LinearLayout,
     * 不能是其他的,因爲其他的Layout(如RelativeLayout)沒有重寫onMeasure(), 所以會在onMeasure()時拋出異常。
     * 
     * @param listView
     */
    private static 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))
                + 5;
        listView.setLayoutParams(params);
    }

另一種方式是複寫ListView的onMeasure方法:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if (isInsideScrollView) {
            int expandSpec = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章