Change PreferenceFragment font via asset fonts
Asked Answered
U

1

9

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;
    }
}

Is there any way to change the font for all segments of PreferenceFragment including dialogs?

Uranous answered 11/12, 2013 at 10:47 Comment(0)
H
2

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>

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;
}

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>

I'm getting a neat result: Preferences with custom font - "Lato"

Hermaphroditism answered 22/10, 2020 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.