Custom Fonts and Custom Textview on Android

我的未来我决定 提交于 2019-11-27 08:04:26

The constructor of TextView calls setTypeface(Typeface tf, int style) with the style parameter retrieved from the XML attribute android:textStyle. So, if you want to intercept this call to force your own typeface you can override this method as follow:

public void setTypeface(Typeface tf, int style) {
    Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/your_normal_font.ttf");
    Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/your_bold_font.ttf");

    if (style == Typeface.BOLD) {
        super.setTypeface(boldTypeface/*, -1*/);
    } else {
        super.setTypeface(normalTypeface/*, -1*/);
    }
}

You can use my CustomTextView which allows you to specify a font file name in your assets folder:

https://github.com/mafshin/CustomTextView

and the usage is really simple:

<com.my.app.CustomTextView
        xmlns:custom="http://schemas.android.com/apk/res/com.my.app"            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Test text"
        android:id="@+id/testcustomview" 

        custom:fontAssetName="Politica XT.otf"
        />

I think it's better to create your own package for custom fonts and import them in your project so that you can use them later in future

  package com.codeslips.utilities;  

  import android.content.Context; 
  import android.graphics.Typeface;
  import android.util.AttributeSet;
  import android.widget.TextView;  

  public class CustomTextView extends TextView {  

          public CustomTextView(Context context)
               { super(context); setFont(); }  

          public CustomTextView(Context context,AttributeSet set)
             { super(context,set); setFont(); } 

          public CustomTextView(Context context,AttributeSet set,int defaultStyle) 
             { super(context,set,defaultStyle); setFont(); } 

          private void setFont() { 

           Typeface typeface=Typeface.createFromAsset(getContext().getAssets(),"fonts/your-font.ttf"); 
           setTypeface(typeface); //function used to set font

             }  
          }

Now use the above class in your XML file to have your custom font

    <com.codeslips.utilities.CustomTextView   
       android:layout_width="wrap_content" 
       android:layout_height="match_parent"
       android:text="Upload Image" 
       android:paddingTop="10sp"
       android:textSize="14sp"
       android:layout_weight="0.7"
       android:textColor="@android:color/white"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!