2013-01-17 73 views
16

我試圖確定繪製之前TextView的高度。我正在使用以下代碼來執行此操作:帶有包裝文本的TextView的getMeasuredHeight()

TextView textView = (TextView) findViewById(R.id.textview); 
textView.setText("TEST"); 
int widthSpec = MeasureSpec.makeMeasureSpec(LayoutParams.MATCH_PARENT, MeasureSpec.EXACTLY); 
int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 
textView.measure(widthSpec, heightSpec); 
System.out.println("MeasuredHeight: " + textView.getMeasuredHeight()); 

輸出爲MeasuredHeight: 28。沒有錯。

然而,當我給TextView長文本字符串,所以包裝時,它仍然給一個單行的高度,而不是兩個:

(...) 
textView.setText("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST"); 
(...) 

輸出是MeasuredHeight: 28,在那裏我會想到MeasuredHeight: 56

爲什麼它不給我正確的價值,我如何才能達到正確的價值?

+0

設置高度也許[這裏] [1]將幫助你,這是幾乎同樣的問題! [1]:http://stackoverflow.com/questions/6157652/android-getmeasuredheight-returns-wrong-values – ObAt

+0

我試過在該線程,並在這一個提議的解決方案(HTTP://計算器.com/questions/4668939/viewgrouptextview-getmeasuredheight-giving-wrong-value-is-smaller-real-real),但它們具有相同的結果。 – nhaarman

+0

你究竟在哪裏使用該代碼? – Luksprog

回答

9

這是一個onCreate方法。您的整個視圖層次結構尚未測量和佈局。所以textView的父母不知道它的寬度。這就是爲什麼textView的尺寸不受其父節的尺寸約束。

試圖改變自己的行:

int widthSpec = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY); 

所以它使你的TextView的寬度等於200個像素。

如果你解釋爲什麼你需要textview的高度,也許我們將能夠幫助你。

+0

現在它確實給出了> 28的高度,但顯然TextView不是200px寬。 – nhaarman

+1

我需要知道'TextView'的高度來創建一個擴展動畫。特別是,我擴展了一個包含多個組件的'ViewGroup'。對於動畫我需要知道要動畫的高度。首先,'ViewGroup'是'GONE',我將高度設置爲'0',將可見性設置爲'VISIBLE',並將高度逐漸增加到測量的高度。 – nhaarman

+0

@Niek:你知道'TextView'的可用寬度嗎?它可能與窗口寬度匹配? –

4

是的,我最近碰到了這個。最好的方法是創建一個ViewTreeObserver對象並註冊一個ViewTreeObserver.OnGlobalLayoutListener。這將在佈局階段之後和繪製階段之前調用。在那時您將能夠獲得TextView的大小。

這不會嚴格地說是文本本身,而是整個TextView。如果涉及內部填充,實際文本將比TextView小。

如果您確實需要實際文本的尺寸,請使用textView.getLayout()獲取文本的Layout對象,然後使用layout.getHeight()。

+0

由於各種原因,我無法使用'OnGlobalLayoutListener'。首先,我需要在佈局的其餘部分繪製完畢後,隨機測量一個'GONE'可見性的'TextView'的高度。 – nhaarman

0

您必須創建自定義的TextView並在佈局中使用它,並使用getActual高度功能在運行時

public class TextViewHeightPlus extends TextView { 
    private static final String TAG = "TextViewHeightPlus"; 
    private int actualHeight=0; 


    public int getActualHeight() { 
     return actualHeight; 
    } 

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

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

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

    } 

    @Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
     super.onSizeChanged(w, h, oldw, oldh); 
     actualHeight=0; 

     actualHeight=(int) ((getLineCount()-1)*getTextSize()); 

    } 

} 
+0

爲什麼在這裏「-1」? –

相關問題