-1

I created an android studio default navgation view and i put two buttons in nav_header_main.xml (see the picture below) now i want to set a custom font for the button. i tried this in MainActivity.java :

 Typeface font = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
    Button b = (Button) findViewById(R.id.login_btn);
    b.setTypeface(font);

but it didn't work!! how can i do this?

Screenshot

mohsen
  • 1
  • 1

1 Answers1

0

You have to write a custom class extending from Button.

Here is an example:

package com.example.test;

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

public class CustomFontButton extends Button {

    public CustomFontButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public CustomFontButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomFontButton(Context context) {
        super(context);
        init();
    }

    private void init() {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
        setTypeface(font);
    }

}

Use it from XML:

<com.example.test.CustomFontButton
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"  
   android:text="Button Text" />
Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61