【android積累】ScrollView和ListView問題


ScrollView和ListView一起使用會有沖突,ListView顯示不全。 如何解決網上也有很多例子,這里只說兩種簡單的方案。

1. 手動計算ListView高度,方法如下:

public static void setListViewHeightBasedOnChildren(ListView listView) {  
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {  
            // pre-condition  
            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);  
    }  

這里使用measuredHeight獲取高度,measuredHeight並不是實際高度,因此該方法計算出的高度與實際的高度會有誤差。

 

2. 重寫ListView的onMeasure方法,重新計算每個子Item的高度

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //根據模式計算每個child的高度和寬度
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM