android TextView 的setTextSize方法的使用
今天,簡單講講android的TextView 的setTextSize方法的使用。
之前,我看代碼時發現了這個函數,于是在網上查詢了這個函數的用法,發現之前自己了解的不夠全面,所以這里記錄一下。
看了看TextView的源碼:
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
我們平時使用setTextSize()的時候都是只用了一個參數,那TypedValue.COMPLEX_UNIT_SP又是個什么鬼?別急來看看下面的代碼:
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()));
}
這是我們在使用setTextView()的時候系統去幫我們做的事,第一個參數是系統默認使用的單位,第二個就是我們設置的文字大小值。那么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也就是系統默認使用的單位。
至此也就清楚了在代碼里面使用setTextView()時,文字的單位也是用的sp。
簡單講講,使用TextView .setTextSize()時,字體的默認單位是sp,也可以自己修改單位,如setTextSize(TypedValue.COMPLEX_UNIT_DIP, size)這里的單位就是dp了。
setTextSize(int unit, int size) 參數的具體意義:
第一個參數可設置如下靜態變量:
TypedValue.COMPLEX_UNIT_PX : Pixels
TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
關鍵代碼
- setTextSize(TypedValue.COMPLEX_UNIT_PX,15); //22像素
- setTextSize(TypedValue.COMPLEX_UNIT_SP,15); //22SP
- setTextSize(TypedValue.COMPLEX_UNIT_DIP,15);//22DIP?
下面舉一些具體的應用:
1.產品中有一個需求是根據TextVIew顯示的內容的大小設置字體大小:
// 優惠券金額為三位數時,更改字體大小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.根據textview長度自動調節文字大小
tv是需要自動調節文字大小的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,因為testPaint.measureText(text)和availableWidth的單位都是px}tv.setTextSize(trySize); }
android TextView 的setTextSize方法的使用就講完了。
就這么簡單。
總結
以上是生活随笔為你收集整理的android TextView 的setTextSize方法的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 使用photoshop
- 下一篇: android 使用SharedPref