1、將自定義字體應(yīng)用于所有TextView
應(yīng)用中我們會經(jīng)常用到自定義字體的TextView。我們需要每次都去設(shè)置TextView的字體。但是,如果您在整個(gè)應(yīng)用程序中多次使用它,那么效率低下(多次分配fontface)和代碼(重復(fù)相同的代碼)是無效的。
2、提供字體內(nèi)存高效
Android手機(jī)內(nèi)存低的時(shí)候已經(jīng)結(jié)束了,但是我們還是應(yīng)該優(yōu)化效率。因此,我們應(yīng)該緩存我們的自定義字體。來自britzl的stackoverflow( britzl on stackoverflow )的解決方案,并調(diào)整了一點(diǎn)寫法:
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
這將緩存字體,同時(shí)最小化對assets文件夾的訪問次數(shù)。現(xiàn)在,由于我們有一種訪問我們的自定義字體的方法,我們來實(shí)現(xiàn)一個(gè)擴(kuò)展TextView的類。
3、擴(kuò)展TextView
接下來,我們將創(chuàng)建一個(gè)新的Java類,它擴(kuò)展了TextView。這允許我們在所有XML視圖中使用該類。它繼承了常規(guī)TextView的所有功能和屬性;但添加我們的自定義字體。
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
applyCustomFont(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
setTypeface(customFont);
}
}
它從我們的FontCache類獲得(希望緩存)字體。最后,我們必須使用字體調(diào)用setTypeface()。
4、使用類
只需在XML視圖中使用該類,它會自動使用您的自定義字體。沒有必要的Java代碼!
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.custom.views.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/green_dark"
android:textSize="20sp"
android:text="Android Studio"
/>
</RelativeLayout>
您可以看到,您可以繼續(xù)使用TextView的所有細(xì)節(jié)(例如textSize,textColor)。現(xiàn)在,只需使用我們剛剛創(chuàng)建的類替換所有<TextView />元素,例如<com.custom.views.CustomTextView />,并且您隨時(shí)應(yīng)用自定義字體!
好了,自定義字體的TextView到這里就結(jié)束了。