ScrollView中巢狀ListView,TextView只顯示一行的高度解決方案

鴨脖發表於2015-06-19

這種情況下,TextView在OnMeasure中只測量了一行的高度,需要重新定義TextView

package com.fyq.xueyou.widget;


import android.app.Activity;
import android.content.Context;
import android.text.Layout;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.widget.LinearLayout;
import android.widget.TextView;


/**
 * 作者:Yelbosh on 2015/6/19 20:07
 * 郵箱:yelbosh@foxmail.com
 * 描述:適用於在ListView中顯示TextView
 * 最近修改:2015/6/19 20:07 by Yelbosh
 */
public class TextViewPlus extends TextView{


    public TextViewPlus(Context context) {
        super(context);
    }


    public TextViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    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)getContext()).getWindowManager().getDefaultDisplay().getWidth();
        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;}
}

相關文章