Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Set custom font to TextView from XML android.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 273
    Comment on it

    In Android development if we want to set custom font to any Button or TextView then we need to do this programmatically.

     

    There is some tricks to set fonts from xml i.e custom Views. 

    There are steps to do that.

    1. Create class with name CustomTextView and extends TextView.

    2. Add required Constructors.

    3. Go to values folder in res. and create attrs.xml file.

    4. Write below code under resources tag.

    <declare-styleable name="ViewCustom">
            <attr name="font" format="string" />
        </declare-styleable>

    5. In CustomTextView class write below code in constructors.  where mFont is String variable.

    TypedArray a = context.getTheme().obtainStyledAttributes(
                    attrs,
                    R.styleable.ViewCustom,
                    0, 0);
            try {
                mFont = a.getString(R.styleable.ViewCustom_font);
            } finally {
                a.recycle();
            }
    
     if (mFont != null) {
                Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/" + mFont);
                setTypeface(tf);
            }

    6. Add fonts to assets/ fonts folder.

    7. Replace TextView with you CustomTextView. like below:-

    <com.example.CustomTextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

    8.  Add font tag to CustomTextView like below :-

    app:font="font_name"

    Note:- font_name is name of font from assets/fonts folder.

    9. Now Run your code and check font style.

     

    Happy Coding!!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: