Change title font of Alert Dialog box

后端 未结 14 1950
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 10:57

I want to change the font of the title of Alert Dialog box.

Can anybody tell how can I do it?

14条回答
  •  太阳男子
    2020-12-16 11:33

    No answers provide a way to change the title typeface of an AlertDialog. Here is what I have done:

    Create the below class:

    public static class TypefaceSpan extends MetricAffectingSpan {
    
      private final Typeface typeface;
    
      public TypefaceSpan(Typeface typeface) {
        this.typeface = typeface;
      }
    
      @Override public void updateDrawState(TextPaint tp) {
        tp.setTypeface(typeface);
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
      }
    
      @Override public void updateMeasureState(TextPaint p) {
        p.setTypeface(typeface);
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
      }
    
    }
    

    Add the following utility method:

    /**
     * 

    Return spannable string with applied typeface in certain style

    * * http://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title * * @param typeface * The typeface to set to the {@link SpannableString} * @param string * the string to place in the span * @return SpannableString that can be used in TextView.setText() method */ public static SpannableString typeface(Typeface typeface, CharSequence string) { SpannableString s = new SpannableString(string); s.setSpan(new TypefaceSpan(typeface), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return s; }

    Finally, set the typeface when creating your AlertDialog:

    Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/your_font.ttf");
    new AlertDialog.Builder(getActivity())
        .setTitle(FontUtils.typeface(typeface, "The title"))
        /* .. */
        .create();
    

提交回复
热议问题