TextVie獲取顯示字符串的寬度之Android開發(fā)
此文通過判斷textview要顯示的字符串的寬度是否超過我設定的寬度,若超過則執(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)了這個方法存在一些問題。當字符串存在字母數(shù)字時,就會有1-2像素的誤差。也正是這個誤差,導致代碼上判斷換行錯誤,使得界面上顯示出錯。
為了解決這個問題,搜到了這篇文章 戳我
這篇文章中使用了另外一個方法測量,沒有new TextPaint,而是使用了TextView自己的TextPaint,這個Paint通過TextView.getPaint()方法獲得。
最后給出一個例子來看這兩種方法的差別。
測試機是MI4,xxdpi
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”時,
測試字符串:測試英文abcd
getMeasuredWidth:279
newPaint measureText:278.0
textView getPaint measureText:279.0
可見使用textView的TextPaint調用measureText方法得到的寬度才是真正的寬度。
通過以上代碼可以順利解決TextView顯示字符串的寬度,希望對大家有所幫助。
- Android字符串和十六進制相互轉化出現(xiàn)的中文亂碼問題
- Android中判斷字符串中必須包含字母或者數(shù)字
- Android獲取手機屏幕寬高、狀態(tài)欄高度以及字符串寬高信息的方法
- android開發(fā)教程之framework增加字符串資源和圖片等resource資源
- Android字符串轉Ascii碼實例代碼
- Android字符串資源文件format方法使用實例
- Android 加密解密字符串詳解
- Android TextView字體顏色設置方法小結
- Android編程實現(xiàn)TextView字體顏色設置的方法小結
- Android 字符串中某個字段可點擊和設置顏色的方法
相關文章
android查看網(wǎng)絡圖片的實現(xiàn)方法
這篇文章主要為大家詳細介紹了android查看網(wǎng)絡圖片的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04Android LayoutInflater加載布局詳解及實例代碼
這篇文章主要介紹了Android LayoutInflater加載布局詳解及實例代碼的相關資料,需要的朋友可以參考下2017-02-02Android 開發(fā)中根據(jù)搜索內容實現(xiàn)TextView中的文字部分加粗
最近遇到一個需求,需要做一個搜索功能。搜索的內容需要加粗顯示。實現(xiàn)方法很簡單,下面通過本文給大家分享Android 開發(fā)中根據(jù)搜索內容實現(xiàn)TextView中的文字部分加粗樣式,非常不錯,需要的朋友參考下2017-03-03android實現(xiàn)ViewPager的Indicator的實例代碼
本篇文章主要介紹了android實現(xiàn)ViewPager的Indicator的實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02