2016-04-16 12 views
3

私は、省略記号を避けるために、利用可能なスペースに応じてテキストをTextViewに設定したいと考えています。例えばAndroid:利用可能なスペースに応じてテキストを設定する方法

:テキストを設定する十分なスペースがある場合

  • 十分なスペースがない場合

  • 「赤いキツネジャンプ」(その結果、「赤いキツネジャンプ」になりますエリプサイズ)テキストを「ジャンプ」に設定する

どうすればいいですか?

答えて

1

Paintオブジェクトで描画したときに、文字列全体の幅を確認するのにPaint.measureText(String)を使用できます。その値がTextViewの幅より大きい場合、テキストが省略されることがわかります。

float totalLength = myPaint.measureText("The red fox jumps"); 
float tvWidth = myTextView.getWidth(); // get current width of TextView 

if (tvWidth < totalLength) { 
    // TextView will display text with an ellipsis 
} 

テキストが切り捨てられることがわかったら、試行錯誤を使って画面に表示できる最小限のテキストを判断できます。この手順はビジネスロジックに依存しますが、最初の手順と同じペイント計算を使用する必要があります。

calculateStringWidth("The red fox jumps"); // too large 
calculateStringWidth("red fox jumps"); // still too large 
calculateStringWidth("fox jumps"); // width is less than TextView, will fit without ellipsis 
+0

偉大な答え! measureTextはピクセル単位で幅を返しますか? –

+0

私はそう信じています、ほとんどのAndroid APIはピクセルを返します。 – fractalwrench

1

1つの方法は、特定のテキストの必要なサイズを計算することです。

textView.setText("The red fox jumps"); 
// call measure is important here 
textView.measure(0, 0); 
int height = textView.getMeasuredHeight(); 
int width = textView.getMeasuredWidth(); 
if (height > availableHeight || width > availableWidth) { 
    textView.setText("jumps"); 
} 

measure()の呼び出しによって、このビューとそのすべての子のサイズ要件が決まります。 Androids View docを参照してください。 Documentation

+0

また良い点。 –

関連する問題