Android - Using Custom Font

后端 未结 21 2136
别跟我提以往
别跟我提以往 2020-11-22 04:38

I applied a custom font to a TextView, but it doesn\'t seems to change the typeface.

Here is my code:

    Typeface myTypeface = Typeface         


        
21条回答
  •  离开以前
    2020-11-22 05:14

    I know there are good answers already, but here's a fully working implementation.

    Here's the custom text view:

    package com.mycompany.myapp.widget;
    
    /**
     * Text view with a custom font.
     * 

    * In the XML, use something like {@code customAttrs:customFont="roboto-thin"}. The list of fonts * that are currently supported are defined in the enum {@link CustomFont}. Remember to also add * {@code xmlns:customAttrs="http://schemas.android.com/apk/res-auto"} in the header. */ public class CustomFontTextView extends TextView { private static final String sScheme = "http://schemas.android.com/apk/res-auto"; private static final String sAttribute = "customFont"; static enum CustomFont { ROBOTO_THIN("fonts/Roboto-Thin.ttf"), ROBOTO_LIGHT("fonts/Roboto-Light.ttf"); private final String fileName; CustomFont(String fileName) { this.fileName = fileName; } static CustomFont fromString(String fontName) { return CustomFont.valueOf(fontName.toUpperCase(Locale.US)); } public Typeface asTypeface(Context context) { return Typeface.createFromAsset(context.getAssets(), fileName); } } public CustomFontTextView(Context context, AttributeSet attrs) { super(context, attrs); if (isInEditMode()) { return; } else { final String fontName = attrs.getAttributeValue(sScheme, sAttribute); if (fontName == null) { throw new IllegalArgumentException("You must provide \"" + sAttribute + "\" for your text view"); } else { final Typeface customTypeface = CustomFont.fromString(fontName).asTypeface(context); setTypeface(customTypeface); } } } }

    Here's the custom attributes. This should go to your res/attrs.xml file:

    
    
        
            
        
    
    

    And here's how you use it. I'll use a relative layout to wrap it and show the customAttr declaration, but it could obviously be whatever layout you already have.

    
    
        
    
    
    

提交回复
热议问题