Android獲取TextView顯示的字符串寬度

工做上有業務須要判斷textview是否換行,個人作法是判斷textview要顯示的字符串的寬度是否超過我設定的寬度,若超過則會執行換行。ide

項目中的其餘地方也有這樣的需求,故直接使用了那一塊的代碼。以下測試

public float getTextWidth(Context Context, String text, int textSize){
TextPaint paint = new TextPaint();
float scaledDensity = Context.getResource().getDisplayMetrics().scaledDensity;
paint.setTextSize(scaledDensity * textSize);
return paint.measureText(text);
}
這裏是使用了TextPaint的measureText方法。字體

不過在項目實踐上發現了這個方法存在一些問題。當字符串存在字母數字時,就會有1-2像素的偏差。也正是這個偏差,致使代碼上判斷換行錯誤,使得界面上顯示出錯。字符串

爲了解決這個問題,搜到了這篇文章 戳我get

這篇文章中使用了另一個方法測量,沒有new TextPaint,而是使用了TextView本身的TextPaint,這個Paint經過TextView.getPaint()方法得到。it

最後給出一個例子來看這兩種方法的差異。class

測試機是MI4,xxdpitest

代碼以下float

public class MainActivity extends Activity {

private final static String TAG = "MainActivity";方法

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 測試字符串
// 測試例子均用15sp的字體大小
String text = "測試中文";

TextView textView = (TextView) findViewById(R.id.test);
textView.setText(text);

int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
textView.measure(spec, spec);

// getMeasuredWidth
int measuredWidth = textView.getMeasuredWidth();

// new textpaint measureText
TextPaint newPaint = new TextPaint();
float textSize = getResources().getDisplayMetrics().scaledDensity * 15;
newPaint.setTextSize(textSize);
float newPaintWidth = newPaint.measureText(text);

// textView getPaint measureText
TextPaint textPaint = textView.getPaint();
float textPaintWidth = textPaint.measureText(text);

Log.i(TAG, "測試字符串:" + text);
Log.i(TAG, "getMeasuredWidth:" + measuredWidth);
Log.i(TAG, "newPaint measureText:" + newPaintWidth);
Log.i(TAG, "textView getPaint measureText:" + textPaintWidth);

}
}
當測試字符串爲: 「測試中文」時,結果以下

測試字符串:測試中文
getMeasuredWidth:180
measureText:180.0
getPaint measureText:180.0
當測試字符串爲: 「測試英文abcd」時,

測試字符串:測試英文abcdgetMeasuredWidth:279newPaint measureText:278.0textView getPaint measureText:279.0可見使用textView的TextPaint調用measureText方法獲得的寬度纔是真正的寬度。

相關文章
相關標籤/搜索