Roboto font in my android app

前端 未结 3 799
名媛妹妹
名媛妹妹 2020-12-05 22:05

Hi i am writing an android app. And I want the roboto font in it irrespective of the version of the phone. Is there a way to do it?

Thanks, Rahim.

3条回答
  •  生来不讨喜
    2020-12-05 22:38

    To set the font in XML is moderately more effort but has the advantage of being able to preview the font inside the Eclipse ADT‘s graphical layout tab of the XML layout editor. Again, first include your custom font .ttf file in the your application’s assets folder.

    Create a custom textview class:

    public class TypefacedTextView extends TextView
    {
     public TypefacedTextView(Context context, AttributeSet attrs)
     {
      super(context, attrs);
    
       // Typeface.createFromAsset doesn't work in the layout editor. Skipping ...
       if (isInEditMode())
       {
        return;
       }
    
       TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView);
       String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface);
       styledAttrs.recycle();
    
       if (fontName != null)
        {
         Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName);
         setTypeface(typeface);
        }
       }
      }
    

    Now to include this custom TypefacedTextView in your XML Layouts simply add your XML namespace attribute below the Android XML namespace attribute:

    
    

    And use your TypefacedTextView as you would a normal TextView in XML but with your own custom tag, remembering to set your font:

    
    

    See my blog post for more info: http://polwarthlimited.com/2013/05/android-typefaces-including-a-custom-font/

提交回复
热议问题