In this tutorial, we can learn how to customise Textview to hold a custom font and can use the textview in the whole project.
STEP 1:-First of all create the Assets Folder if it's not created already, Copy the font you want to use in your project.
STEP 2:- Create an attrs,xml in in res/values
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomFontTextView"> <attr name="fontName" format="string" /> </declare-styleable> </resources>![]()
STEP 3:- Create a Java class CustomFontTextView.java
public class CustomFontTextView extends AppCompatTextView { public CustomFontTextView(Context context) { super(context); } public CustomFontTextView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public CustomFontTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, 0, 0); String fontName = a.getString(R.styleable.CustomFontTextView_fontName); Typeface face = null; if (fontName != null && !TextUtils.isEmpty(fontName)) { face = Typeface.createFromAsset(context.getAssets(), fontName); } else { face = Typeface.createFromAsset(context.getAssets(), "Steelworks Vintage Demo.ttf"); } this.setTypeface(face); a.recycle(); } }
STEP 4:- Then create main_activity.xml like below
<com.cretlabs.customfonttextview.customviews.CustomFontTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="12dp" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:gravity="center" android:text="@string/app_name" android:textSize="20sp" app:fontName="@string/steel_work_font" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toTopOf="parent" tools:layout_editor_absoluteX="12dp" tools:ignore="MissingConstraints" />
STEP 5:-Add your font file name in strings.xml
<string name="steel_work_font">Steelworks Vintage Demo.ttf</string>
Add font name to Custom text view in activity_main.xml like below
app:fontName="@string/steel_work_font"
As you wish, you can add multiple fonts to assets and use one by one in your project.
See full article http://thoughtnerds.com/create-custom-textview-android-with-typeface-example/