簡體   English   中英

如何在Android中為整個應用程序設置自定義字體

[英]How to set a custom font for the entire application in Android

好的,所以我對此進行了研究,發現了一些與該主題相關的代碼,但是當我嘗試時似乎不起作用。 我不得不分別更改每個文本視圖的字體,這讓我發瘋。 到目前為止,我所做的是創建一個將覆蓋字體的類:

public final class FontsOverride {

public static void setDefaultFont(Context context,
                                  String staticTypefaceFieldName, String fontAssetName) {
    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
                                  final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
}

然后,每次我希望覆蓋每個類中的字體時,我都會試圖暗示這一點:

   FontsOverride.setDefaultFont(this, "DEFAULT", "ComicRelief.ttf");

必須有一種簡單的方法來執行此操作,而我已經嘗試了好幾個小時,但仍無法解決。

只需創建一個自定義TextView類:

public class CustomTextView extends TextView {

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        load();
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        load();
    }

    public CustomTextView(Context context) {
        super(context);
        load();
    }

    public void load() {
        setTypeface(
            Typeface.createFromAsset(getContext().getAssets(), "pacifico.ttf"), 1
        );
    }

}

將自定義視圖應用於所需的任何TextView:

<com.your.package.views.CustomTextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

現在已聲明您的TextView類型並將其強制轉換為CustomTextView:

CustomTextView myTextView = (CustomTextView) findViewById(R.id.my_text_view);

並記住將適當的字體放入資產文件夾中(在本示例中為“ pacifico.ttf”)。

您需要使用書法庫為整個應用程序設置自定義字體。

在您的自定義Application類中,在onCreate()內初始化Calligraphy:

CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                        .setDefaultFontPath("fonts/custom_font.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build());

在這里, custom_font.ttf是您要應用於整個應用程序的字體,它需要駐留在assets/fonts文件夾中。

其次,您需要重寫Activity類中的attachBaseContext()方法,如下所示:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

現在,您在應用程序中看到的每個文本都具有您通過書法設置為默認字體的字體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM