天天看點

解決ScrollView嵌套ListView,清單項高度不同,顯示不全的問題

ScrollView嵌套ListView,首先碰到的問題,就是ListView隻顯示一個清單項,其他的不顯示,解決方法:getView方法傳回的View的必須由LinearLayout組成,因為隻有LinearLayout才有measure()方法

//解決ScrollView嵌套ListView隻顯示一行
    public static void setListViewHeightBasedOnChildren(ListView listView)
    {
        // 擷取ListView對應的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null)
        {
            return;
        }

        int totalHeight = ;
        for (int i = , len = listAdapter.getCount(); i < len; i++)
        {
            // listAdapter.getCount()傳回資料項的數目
            View listItem = listAdapter.getView(i, null, listView);
            // 計算子項View 的寬高
            listItem.measure(, );
            // 統計所有子項的總高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - ));
        // listView.getDividerHeight()擷取子項間分隔符占用的高度
        // params.height最後得到整個ListView完整顯示需要的高度
        listView.setLayoutParams(params);
    }
           

在listview.setAdapter(adapter);後調用

另一問題,如果listview清單項的高度是動态改變的,比如在清單項中包含ExpandableTextView之類的控件,有可能會出現最後幾項顯示不全的問題,解決方法是重新寫一個ListView:

public class ListViewForDifferentHeightItems extends ListView
{
    public ListViewForDifferentHeightItems(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public ListViewForDifferentHeightItems(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ListViewForDifferentHeightItems(Context context) {
        super(context);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> ,MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
           

繼續閱讀