android TextView 的setTextSize方法的使用
今天,簡(jiǎn)單講講android的TextView 的setTextSize方法的使用。
之前,我看代碼時(shí)發(fā)現(xiàn)了這個(gè)函數(shù),于是在網(wǎng)上查詢(xún)了這個(gè)函數(shù)的用法,發(fā)現(xiàn)之前自己了解的不夠全面,所以這里記錄一下。
看了看TextView的源碼:
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
我們平時(shí)使用setTextSize()的時(shí)候都是只用了一個(gè)參數(shù),那TypedValue.COMPLEX_UNIT_SP又是個(gè)什么鬼?別急來(lái)看看下面的代碼:
public void setTextSize(int unit, float size) {
Context c = getContext();
Resources r;
if (c == null)
r = Resources.getSystem();
else
r = c.getResources();
setRawTextSize(TypedValue.applyDimension(
unit, size, r.getDisplayMetrics()));
}
這是我們?cè)谑褂胹etTextView()的時(shí)候系統(tǒng)去幫我們做的事,第一個(gè)參數(shù)是系統(tǒng)默認(rèn)使用的單位,第二個(gè)就是我們?cè)O(shè)置的文字大小值。那么TypedValue.COMPLEX_UNIT_SP到底是什么呢?
public static final int COMPLEX_UNIT_PX = 0;
/** {@link #TYPE_DIMENSION} complex unit: Value is Device Independent
*? Pixels. */
public static final int COMPLEX_UNIT_DIP = 1;
/** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */
public static final int COMPLEX_UNIT_SP = 2;
不難看出0是代表px,1是dp,2是sp也就是系統(tǒng)默認(rèn)使用的單位。
至此也就清楚了在代碼里面使用setTextView()時(shí),文字的單位也是用的sp。
簡(jiǎn)單講講,使用TextView .setTextSize()時(shí),字體的默認(rèn)單位是sp,也可以自己修改單位,如setTextSize(TypedValue.COMPLEX_UNIT_DIP, size)這里的單位就是dp了。
setTextSize(int unit, int size) 參數(shù)的具體意義:
第一個(gè)參數(shù)可設(shè)置如下靜態(tài)變量:
TypedValue.COMPLEX_UNIT_PX : Pixels
TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
關(guān)鍵代碼
- setTextSize(TypedValue.COMPLEX_UNIT_PX,15); //22像素
- setTextSize(TypedValue.COMPLEX_UNIT_SP,15); //22SP
- setTextSize(TypedValue.COMPLEX_UNIT_DIP,15);//22DIP?
下面舉一些具體的應(yīng)用:
1.產(chǎn)品中有一個(gè)需求是根據(jù)TextVIew顯示的內(nèi)容的大小設(shè)置字體大小:
// 優(yōu)惠券金額為三位數(shù)時(shí),更改字體大小if (couponAmunt.length() >= 3) {holder.favourItemPriceUnit.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); holder.favourItemPrice.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);} else { holder.favourItemPrice.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 36); holder.favourItemPriceUnit.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);}
2.根據(jù)textview長(zhǎng)度自動(dòng)調(diào)節(jié)文字大小
tv是需要自動(dòng)調(diào)節(jié)文字大小的Textview Paint testPaint = tv.getPaint(); String text = tv.getText().toString(); int textWidth = tv.getMeasureWidth(); if (textWidth > 0) {int availableWidth = textWidth - tv.getPaddingLeft() -tv.getPaddingRight();float trySize = tv.getTextSize();testPaint.setTextSize(trySize);while ((testPaint.measureText(text) > availableWidth)) {trySize -= 2;tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,?trySize);?? //這里必須使用px,因?yàn)閠estPaint.measureText(text)和availableWidth的單位都是px}tv.setTextSize(trySize); }
android TextView 的setTextSize方法的使用就講完了。
就這么簡(jiǎn)單。
總結(jié)
以上是生活随笔為你收集整理的android TextView 的setTextSize方法的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: android 使用photoshop
- 下一篇: android 使用SharedPref