怎么動態(tài)設(shè)置粗體:
Android中的粗體大家都知道怎么設(shè)置,就是在 xml 中設(shè)置一個textStyle贱呐,但怎么動態(tài)的設(shè)置粗體呢,Android 的Textview中沒有直接設(shè)置setTextBold
這樣的API入桂,我這有兩個辦法去解決:
1.獲取TextView的Paint奄薇,paint 中有個方法是setFakeBoldText
,代碼演示就是
mTextView.getPaint().setFakeBoldText(true);
這個達到的效果是和設(shè)置 textStyle效果一致抗愁。
2.通過setTypeface( Typeface tf, @Typeface.Style int style)
,看下Typeface.Style
的結(jié)構(gòu)
/** @hide */
@IntDef(value = {NORMAL, BOLD, ITALIC, BOLD_ITALIC})
@Retention(RetentionPolicy.SOURCE)
public @interface Style {}
是不是很熟悉啊馁蒂,這不就是對應(yīng)的textStyle中的三個參數(shù)嗎
代碼演示就是:
mText.setTypeface(null, Typeface.BOLD);
咱們看一下源碼
public void setTypeface(@Nullable Typeface tf, @Typeface.Style int style) {
if (style > 0) {
if (tf == null) {
tf = Typeface.defaultFromStyle(style); //typeface 是可以為null的,為null 就用默認的
} else {
tf = Typeface.create(tf, style);
}
setTypeface(tf);// 調(diào)用了 重載的函數(shù)蜘腌,里面主要是把tf 傳入到 textpaint里面操作
// now compute what (if any) algorithmic styling is needed
int typefaceStyle = tf != null ? tf.getStyle() : 0;
int need = style & ~typefaceStyle;
mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);// 其實和方法一殊途同歸
mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
} else {
mTextPaint.setFakeBoldText(false);
mTextPaint.setTextSkewX(0);
setTypeface(tf);
}
}
其實上面整體方法的思想還是通過 TextView里面的TextPaint 去設(shè)置 沫屡。
怎能設(shè)置中粗
我在開發(fā)的過程中,總會遇到設(shè)計給出的設(shè)置粗體和中粗的字重撮珠,一開始我們都以為中粗也是粗體沮脖,都用的 BOLD 的樣式,但是經(jīng)過對比芯急,中粗比常規(guī)字體要粗勺届,比粗體要細。那么要設(shè)置這個就要用到 fontFamily
android:fontFamily="sans-serif-medium"
Typeface typeface = Typeface.create("sans-serif-medium", 0);
mText.setTypeface(typeface);
參考鏈接:https://blog.csdn.net/yuanxw44/article/details/80019501