androidfontsxml-attribute

Is it possible to use fancy fonts in Android?


I know that the TextView has an attribute called fontFamily and I thought you can change the font of the text by changing the value of this attribute. So I wrote:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="my text"
    android:fontFamily="OCR A Std"
    android:textSize="20pt"/>

And then I run the app but the font of the text is still in the plain old Arial-like font. I think there must be a way to use fancy fonts in android, right?

If I just can't use fancy fonts, what font(s) do(es) android support? Only Arial is impossible, right?


Solution

  • you should do it in this way

    first create a folder named assets and create another folder within it named as fonts now paste some .ttf fonts file into it lets say you've file named as neutra_bold.ttf

    now create a class that extends TextView for eg.

    package com.view9.costumviews;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class NeutraBoldTextView extends TextView {
    
        public NeutraBoldTextView(Context context) {
            super(context);
            Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/neutra_bold.ttf");
            this.setTypeface(face);
        }
    
        public NeutraBoldTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/neutra_bold.ttf");
            this.setTypeface(face);
        }
    
        public NeutraBoldTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/neutra_bold.ttf");
            this.setTypeface(face);
        }
    
        protected void onDraw (Canvas canvas) {
            super.onDraw(canvas);
    
    
        }
    
    }
    

    now to use this view you can do this in xml layout like this

    <com.view9.costumviews.NeutraBoldTextView
    
                    android:id="@+id/tvViewAttachmentDescLabel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="20dp"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:text="@string/text_description"
                    android:textColor="@color/heading_text_color"
                     />