通过用户设置更改应用程序中特定文本的字体

Changing Font for specific texts in the App by User Settings

我正在 Java 的 Android Studio 开发日语词汇应用程序。 我想让用户能够 select 最适合他们偏好的字体。

目前,我有一个字体添加到 res 并使用字体文件定义了一个字体系列。应用程序中的所有日文文本(文本框、按钮等)都使用此字体系列。

当应用程序处于 运行 时,有没有办法更改字体系列本身或更改 xml 中使用此字体系列的每个元素的字体系列标记值对。

这是我当前的字体系列定义

<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/kosugimaru_regular"/>
    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/kosugimaru_regular" />
</font-family>

这就是我在 xml 中使用此字体系列的方式:

    <TextView
        android:id="@+id/TV_KanjiChar"
        android:fontFamily="@font/kanji_default"
        android:text="学"
        android:textSize="60sp" 
        ...
        />

如果在 运行 应用程序时无法更改该绑定,是否有另一种优雅的方法来解决此问题?我想避免在每个 activity 中使用更新函数来动态更改字体系列 onCreate。

我继续回答我的问题。

一个非常优雅的解决方案是创建一个 Textview 和 Button 的子类,并向构造函数添加一个 UpdateFont 函数。

public class KanjiTextView extends AppCompatTextView {
    public KanjiTextView(Context context) {
        super(context);
        updateFont();
    }

    public KanjiTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        updateFont();
    }

    public KanjiTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        updateFont();

    }

    public void updateFont()
    {
        int font_res = get_user_selected_font();

        Typeface typeface = getFont(getContext(), font_res.get_Res());
        setTypeface(typeface);
    }
}

_____________________________________________________________________________


      <com.[package].KanjiTextView
            android:id="@+id/TV_Kanjitext"
            android:text="学校"
            android:textAlignment="center"
            android:textSize="30sp"
            ...
            />