判斷ListView的每一個item高度

前提 這個item的根view必須是LinearLayout

package com.bxg.news.view;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utility {
 public static void setListViewHeightBasedOnChildren(ListView listView,
   View v) {
  // 獲取ListView對應的Adapter
  ListAdapter listAdapter = listView.getAdapter();
  if (listAdapter == null) {
   // pre-condition
   return;
  }

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

  if (v != null) {
   totalHeight += v.getHeight();
  }

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

這裏需要注意的是:
如果TextView是多行的時候。需要對TextView進行重寫onmeasure方法

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);

  Layout layout = getLayout();
  if (layout != null) {
   int height = (int) FloatMath.ceil(getMaxLineHeight(this.getText()
     .toString()))
     + getCompoundPaddingTop()
     + getCompoundPaddingBottom();
   int width = getMeasuredWidth();
   setMeasuredDimension(width, height);
  }
 }

 private float getMaxLineHeight(String str) {
  float height = 0.0f;
  float screenW = ((Activity) context).getWindowManager()
    .getDefaultDisplay().getWidth();
  float paddingLeft = ((RelativeLayout) this.getParent())
    .getPaddingLeft();
  float paddingReft = ((RelativeLayout) this.getParent())
    .getPaddingRight();
  // 這裏具體this.getPaint()要注意使用,要看你的TextView在什麼位置,這個是拿TextView父控件的Padding的,爲了更準確的算出換行
  int line = (int) Math.ceil((this.getPaint().measureText(str) / (screenW
    - paddingLeft - paddingReft)));
  height = (this.getPaint().getFontMetrics().descent - this.getPaint()
    .getFontMetrics().ascent) * line;
  return height;
 }

歡迎關注我的微信公衆號: androidesigner 。 一起學習,一起進步

二維碼

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