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

时间:2019-08-26 11:49:48

标签: java android-studio fonts settings

我正在用Java的Android Studio开发日语词汇应用程序。 我想让用户选择最适合那里的首选项的字体。

当前,我将字体添加到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" 
        ...
        />

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

1 个答案:

答案 0 :(得分:0)

我要回答我的问题。

一个非常优雅的解决方案是创建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"
            ...
            />

相关问题