1. 程式人生 > >Android開發————ListView內部Item高度設定

Android開發————ListView內部Item高度設定

1、前言

從谷歌那裡找到的ScrollView巢狀ListView只顯示一行的解決辦法相信很多人都遇到過,然後大部分都是用這位博主的辦法解決的吧

剛開始我也是用這個辦法解決的,首先感謝這位哥的大私奉獻,貼上地址

2、解決的核心程式碼

  1. public void setListViewHeightBasedOnChildren(ListView listView) {     
  2.         // 獲取ListView對應的Adapter     
  3.         ListAdapter listAdapter = listView.getAdapter();     
  4.         if (listAdapter
     == null) {     
  5.             return;     
  6.         }     
  7.         int totalHeight = 0;     
  8.         for (int i = 0len = listAdapter.getCount(); i <len; i++) {     
  9.             // listAdapter.getCount()返回資料項的數目     
  10.             View listItem = listAdapter.getView(i, null, listView);     
  11.             // 計運算元項View 的寬高     
  12.             listItem.measure(0, 0);      
  13.             // 統計所有子項的總高度     
  14.             totalHeight += listItem.getMeasuredHeight();      
  15.         }     
  16.         ViewGroup.LayoutParams params = listView.getLayoutParams();     
  17.         params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));     
  18.         // listView.getDividerHeight()獲取子項間分隔符佔用的高度     
  19.         // params.height最後得到整個ListView完整顯示需要的高度     
  20.         listView.setLayoutParams(params);     
  21.     }     
這個程式碼讓控制元件去計算Listview自己的高度然後設定這個Listview的高度

但是這個程式碼裡面有一個問題,就是這個當你的ListView裡面有多行的TextView的話,ListView的高度就會計算錯誤,它只算到了一行TextView的高度,

這個問題在so上的概述為以下:

3、終極解決辦法

這個問題頭疼了一陣後,查找了一下,應該重寫一個TextView的onMeasure方法比較好解決

程式碼有

  1. @Override
  2.     protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  4.         Layout layout = getLayout();  
  5.         if (layout != null) {  
  6.             int height = (int)FloatMath.ceil(getMaxLineHeight(this.getText().toString()))  
  7.                     + getCompoundPaddingTop() + getCompoundPaddingBottom();  
  8.             int width = getMeasuredWidth();              
  9.             setMeasuredDimension(width, height);  
  10.         }  
  11.     }  
  12.     privatefloat getMaxLineHeight(String str) {  
  13.         float height = 0.0f;  
  14.         float screenW = ((Activity)context).getWindowManager().getDefaultDisplay().getWidth();  
  15.         float paddingLeft = ((LinearLayout)this.getParent()).getPaddingLeft();  
  16.         float paddingReft = ((LinearLayout)this.getParent()).getPaddingRight();  
  17. //這裡具體this.getPaint()要注意使用,要看你的TextView在什麼位置,這個是拿TextView父控制元件的Padding的,為了更準確的算出換行
  18.  int line = (int) Math.ceil( (this.getPaint().measureText(str)/(screenW-paddingLeft-paddingReft))); height = (this.getPaint().getFontMetrics().descent-this.getPaint().getFontMetrics().ascent)*line; return height;}  


上面的程式碼完成更能為,在ListView開始測量時,測量到TextView時,就呼叫我們的onMeasure方法,我們就可以測量字型的總寬度除與去掉邊距的螢幕的大小,就可以算出文字要幾行來顯示,然後測量字型的高度*行數可以得到字型的總高度,然後在加上上下邊距就是TextView真正的高度,然後setMeasuredDimension進去就可以計算出正確的值出來。