通过资产字体更改PreferenceFragment字体 [英] Change PreferenceFragment font via asset fonts
问题描述
为了在PreferenceFragment中为每个首选项设置自定义字体,我必须为每个首选项类型( CustomSwitchPreference
, CustomEditTextPreference
, CustomListPreference
,....),并在 onBindView
方法中设置其字体.
In order to have custom fonts for each Preference in PreferenceFragment, I had to write a new customized class for each preference type (CustomSwitchPreference
, CustomEditTextPreference
, CustomListPreference
,....) and set its font in onBindView
method.
它有效,但这是最好的解决方案吗?没有矮个子了吗?
It works, but is this best solution? No shorter one?
@Override
public void onBindView(View view){
super.onBindView(view);
TextView title = (TextView) view.findViewById(android.R.id.title);
TextView summary = (TextView) view.findViewById(android.R.id.summary);
Utils.setFont(context, title, customfont);
Utils.setFont(context, summary, customfont);
}
public class Utils{
public static boolean setFont(Context context, TextView tv, String fontAssetName) {
Typeface font = Typeface.createFromAsset(context.getResources().getAssets(), fontAssetName);
if (font != null) {
tv.setTypeface(font);
return true;
}
return false;
}
}
是否可以更改 PreferenceFragment
的所有段(包括对话框)的字体?
Is there any way to change the font for all segments of PreferenceFragment
including dialogs?
推荐答案
在您的styles.xml中,添加以下样式:
In your styles.xml, add the following style:
<style name="PreferenceTheme" parent="@style/AppTheme">
<item name="android:fontFamily">@font/lato</item>
<item name="fontFamily">@font/lato</item>
</style>
然后,在SettingsFragment.java中,覆盖onCreateView():
Then, in SettingsFragment.java, override the onCreateView():
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
container.getContext().setTheme(R.style.PreferenceTheme);
return view;
}
通常可以解决问题.如果没有,请将样式添加到AndroidManifest.xml:
This usually does the trick. If not, add the style to AndroidManifest.xml:
<application
...>
<activity.../>
<activity
android:name=".SettingsActivity"
android:theme="R.style.PreferenceTheme"/>
...
</application>
我得到了一个整洁的结果:使用自定义字体的首选项-"Lato"
I'm getting a neat result: Preferences with custom font - "Lato"
这篇关于通过资产字体更改PreferenceFragment字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!