Set typeface with custom font for alert dialog ite

2019-06-11 01:14发布

I'm creating an alert dialog this way:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());
alertDialog.setCustomTitle(null);
alertDialog.setItems(getAllListNames(), new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialogInterface, int i) {
      //Doing something awesome...
  }
});

I know it creates a list view with my items, I want to set a typeface with a custom font for them and also set a max number of characters for each list item, how can I do it?

1条回答
在下西门庆
2楼-- · 2019-06-11 01:31

You have to create a custom theme. Here is the official guide: http://developer.android.com/guide/topics/ui/themes.html :)

Something like this (in the style.xml file):

<style name="CustomFontTheme" parent="android:Theme.Light">
    <item name="android:textViewStyle">@style/MyTextViewStyle</item>
    <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

<style name="MyTextViewStyle" parent="android:Widget.TextView">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyButtonStyle" parent="android:Widget.Holo.Button">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

Then when you create the dialog you can do this:

Context context = new ContextThemeWrapper(view.getContext(), R.style.CustomFontTheme)
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

Where R.style.CustomFontTheme is the id for the them you have created.


Update:

Ok, to add your custom typeface you can follow this gist: https://gist.github.com/artem-zinnatullin/7749076

The key is to override the a given font face when the application starts like this:

TypefaceUtil.overrideFont(getApplicationContext(), "AWESOME-FONT", "fonts/Awesome-Font.ttf");

the gist has the implementation for that method.

So the theme styles should look like this now:

<style name="MyTextViewStyle" parent="android:Widget.TextView">
    <item name="android:fontFamily">awesome-font</item>
</style>

<style name="MyButtonStyle" parent="android:Widget.Holo.Button">
    <item name="android:fontFamily">awesome-font</item>
</style>
查看更多
登录 后发表回答