此文通過判斷textview要顯示的字符串的寬度是否超過我設(shè)定的寬度,若超過則執(zhí)行換行,具體代碼講解如下:
項目中的其他地方也有這樣的需求,故直接使用了那一塊的代碼。
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方法。
不過在項目實踐上發(fā)現(xiàn)了這個方法存在一些問題。當(dāng)字符串存在字母數(shù)字時,就會有1-2像素的誤差。也正是這個誤差,導(dǎo)致代碼上判斷換行錯誤,使得界面上顯示出錯。
為了解決這個問題,搜到了這篇文章 戳我
這篇文章中使用了另外一個方法測量,沒有new TextPaint,而是使用了TextView自己的TextPaint,這個Paint通過TextView.getPaint()方法獲得。
最后給出一個例子來看這兩種方法的差別。
測試機是MI4,xxdpi
public class MainActivity extends Activity {private final static String TAG = "MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 測試字符串
// 測試?yán)泳?5sp的字體大小
String text = "測試中文";
TextView textView = (TextView) findViewById(R.id.test);textView.setText(text);int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);textView.measure(spec, spec);// getMeasuredWidthint measuredWidth = textView.getMeasuredWidth();// new textpaint measureTextTextPaint newPaint = new TextPaint();float textSize = getResources().getDisplayMetrics().scaledDensity * 15;newPaint.setTextSize(textSize);float newPaintWidth = newPaint.measureText(text);// textView getPaint measureTextTextPaint 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);}}
當(dāng)測試字符串為: “測試中文”時,結(jié)果如下
測試字符串:測試中文
getMeasuredWidth:180
measureText:180.0
getPaint measureText:180.0
當(dāng)測試字符串為: “測試英文abcd”時,
測試字符串:測試英文abcd
getMeasuredWidth:279
newPaint measureText:278.0
textView getPaint measureText:279.0
可見使用textView的TextPaint調(diào)用measureText方法得到的寬度才是真正的寬度。
通過以上代碼可以順利解決TextView顯示字符串的寬度,希望對大家有所幫助。
新聞熱點
疑難解答
圖片精選