为了在 PreferenceFragment 中为每个 Preference 设置自定义字体,我必须为每个 preference 类型编写一个新的自定义类(CustomSwitchPreference
、CustomEditTextPreference
, CustomListPreference
,....) 并在 onBindView
方法中设置其字体。
它有效,但这是最佳解决方案吗?没有更短的吗?
@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
的所有部分(包括对话框)的字体吗?
最佳答案
在您的 styles.xml 中,添加以下样式:
<style name="PreferenceTheme" parent="@style/AppTheme">
<item name="android:fontFamily">@font/lato</item>
<item name="fontFamily">@font/lato</item>
</style>
然后,在 SettingsFragment.java 中,覆盖 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 中:
<application
...>
<activity.../>
<activity
android:name=".SettingsActivity"
android:theme="R.style.PreferenceTheme"/>
...
</application>
我得到了一个整洁的结果: Preferences with custom font - "Lato"
关于android - 通过 Assets 字体更改 PreferenceFragment 字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20517068/