2014-06-23 76 views
11

中以編程方式查找TextView的文本區域(高度/寬度)我有一個EditText,ButtonTextView。點擊按鈕時,textview顯示用edittext編寫的文本。是否有可能找到文本視圖的大小取決於文本。即如果它有三個字符「abc」,現在寬度是多少,如果它有5個字符,如「abcde」,那麼寬度是多少?如何在android

回答

52
Rect bounds = new Rect(); 
Paint textPaint = textView.getPaint(); 
textPaint.getTextBounds(text,0,text.length(),bounds); 
int height = bounds.height(); 
int width = bounds.width(); 

textView.setText("bla"); 
textView.measure(0, 0); 
textView.getMeasuredWidth(); 
textView.getMeasuredHeight(); 
+0

偉大的工作...日Thnx。 –

+0

像一個魅力工作 –

2

試試這個辦法,希望這將幫助你解決你的問題。

yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
    int width = yourTextView.getMeasuredWidth(); 
    int height = yourTextView.getMeasuredHeight(); 

    } 
}); 
+0

你好@MD,你可以看看http://stackoverflow.com/questions/25196894/how-to-get-list-item-data-in-bindview-when-clicking-on -radiobutton-in-android –

7

請試試這個:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    TextView edit = (TextView) findViewById(R.id.edit); 
    edit.setTextSize(20);  
    edit.setText("Hello, world");  
    edit.measure(0, 0); 
    int width = edit.getMeasuredWidth(); 
    Log.w("width", width.toString()); 
} 

之前你得到寬度,你必須衡量視圖/標籤/文本編輯。 請讓我知道如果這不起作用。

+0

這兩個答案都是正確的,你和上面那個...... Thnx的工作。 –

+0

歡迎標記爲答案(下面的投票) 我很高興它的工作。 – Iosif

2

請告訴我寬度在???你要嗎 ?

TextView方法getWidth()讓你寬您的視圖,以像素爲單位

TextView textView = (TextView)findViewById(R.id.textview); 
textView.getWidth(); //width of your view, in pixels 
+0

我的意思是根據文字找到寬度。 –

0
TextView txt = new TextView(mContext); 
txt.setText("Some Text)"; 
int height = txt.getLineCount() * txt.getLineHeight(); 
int width = txt.getWidth();