中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

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

2018-07-20    來(lái)源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

工作上有業(yè)務(wù)需要判斷textview是否換行,我的做法是判斷textview要顯示的字符串的寬度是否超過(guò)我設(shè)定的寬度,若超過(guò)則會(huì)執(zhí)行換行。

項(xiàng)目中的其他地方也有這樣的需求,故直接使用了那一塊的代碼。如下

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方法。

不過(guò)在項(xiàng)目實(shí)踐上發(fā)現(xiàn)了這個(gè)方法存在一些問(wèn)題。當(dāng)字符串存在字母數(shù)字時(shí),就會(huì)有1-2像素的誤差。也正是這個(gè)誤差,導(dǎo)致代碼上判斷換行錯(cuò)誤,使得界面上顯示出錯(cuò)。

為了解決這個(gè)問(wèn)題,搜到了這篇文章 戳我

這篇文章中使用了另外一個(gè)方法測(cè)量,沒(méi)有new TextPaint,而是使用了TextView自己的TextPaint,這個(gè)Paint通過(guò)TextView.getPaint()方法獲得。

最后給出一個(gè)例子來(lái)看這兩種方法的差別。

測(cè)試機(jī)是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);
		
		// 測(cè)試字符串
		// 測(cè)試?yán)泳?5sp的字體大小
		String text = "測(cè)試中文";
		
		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, "測(cè)試字符串:" + text);
		Log.i(TAG, "getMeasuredWidth:" + measuredWidth);
		Log.i(TAG, "newPaint measureText:" + newPaintWidth);
		Log.i(TAG, "textView getPaint measureText:" + textPaintWidth);
		
	}
}

當(dāng)測(cè)試字符串為: “測(cè)試中文”時(shí),結(jié)果如下

測(cè)試字符串:測(cè)試中文
getMeasuredWidth:180
measureText:180.0
getPaint measureText:180.0 

當(dāng)測(cè)試字符串為: “測(cè)試英文abcd”時(shí),

測(cè)試字符串:測(cè)試英文abcd
getMeasuredWidth:279
newPaint measureText:278.0
textView getPaint measureText:279.0 

可見使用textView的TextPaint調(diào)用measureText方法得到的寬度才是真正的寬度。



來(lái)自:http://2kpurple.github.io/2014/11/02/get-text-view-text-width/    

標(biāo)簽: isp 代碼

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:AppUtils用于獲取程序版本信息,程序名稱的Android工具類

下一篇:JAVA支持HTTP斷點(diǎn)續(xù)傳