android - 通过 Assets 字体更改 PreferenceFragment 字体

标签 android android-fragments customization android-preferences

为了在 PreferenceFragment 中为每个 Preference 设置自定义字体,我必须为每个 preference 类型编写一个新的自定义类(CustomSwitchPreferenceCustomEditTextPreference, 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/

相关文章:

WorldPay 自定义 CSS 文件支持的 CSS 属性

visual-studio-2008 - 在 VS2008 中更改右键单击上下文菜单选项

java - android studio android.support.design.widget.CoordinatorLayout 中的渲染问题

android - Play 商店报告 "Your device isn' t 与此版本兼容”但它通过 adb 在 Nexus7 上安装得很好

android - fragment 中的 ViewPager

Android Activity 和 Fragment 之间的通信

android - 具有 3 个 fragment 的 ViewPager 从中间 fragment 的两侧加载 fragment

多次触发 Scrollview 的 Android onScrollChanged

android - 如何使用 android :layout attribute 为自定义首选项实例化布局

python - Emacs:设置/重置 python 调试断点