我正在用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。
发布于 2019-08-27 21:28:15
我将继续回答我的问题。
一个非常优雅的解决方案是创建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"
...
/>https://stackoverflow.com/questions/57657392
复制相似问题