標籤:listview高度 android
有些頁面中ListView只是整個頁面的一小部分,需要上下滑動整個頁面,ListView不讓自己滑動,預設ListView只會顯示第一個item。這個時候需要重新設定一下ListView的高度。如果ListView的item中有TextView並且TextView的行數大於1行,這個時候.重設ListView的高度卻計算不出TextView的高度,會出現TextView只顯示一行的情況。這個時候需要使用自訂的TextView,並且不要設定MaxLines這個屬性。
設定ListView高度的代碼:
public static void SetHeigth(ListView list) { ListAdapter listAdapter = list.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; i++) { View listItem = listAdapter.getView(i, null, list); // listItem.measure(LinearLayout.LayoutParams.MATCH_PARENT,0); listItem.measure(0,0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = list.getLayoutParams(); params.height = totalHeight+ (list.getDividerHeight() * (listAdapter.getCount() - 1)); list.setLayoutParams(params); }
自訂TextView的代碼:
public class MyTextView extends TextView { private Context context; public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub this.context=context; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); Layout layout = getLayout(); if (layout != null) { int height = (int)Math.ceil(getMaxLineHeight(this.getText().toString())) + getCompoundPaddingTop() + getCompoundPaddingBottom(); int width = getMeasuredWidth(); setMeasuredDimension(width, height); } } private float getMaxLineHeight(String str){ float height = 0.0f; float screenW = context.getResources().getDisplayMetrics().widthPixels; float paddingLeft = ((LinearLayout)this.getParent()).getPaddingLeft(); float paddingReft = ((LinearLayout)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; } }
本文出自 “Focus_000” 部落格,請務必保留此出處http://120806872.blog.51cto.com/8289253/1606199
Android ListView高度問題