0

What is the easiest and fastest way to change font to android project, I want to avoid changing every single view.

user1684140
  • 444
  • 6
  • 18

2 Answers2

1

Use Calligraphy

by using this library you don't need to change every view, just create a custom Activity class and override this method:

@Override
protected void attachBaseContext(Context newBase) {
   super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

and then extend all of your activities with this activity.

Moh Mah
  • 2,005
  • 20
  • 29
0

You can make Custom View for all View.

For eg. for TextView:

 public class MyTextView extends TextView {
    private Typeface typeface;

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.app);
        String customFont = a.getString(R.styleable.app_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    private boolean setCustomFont(Context ctx, String asset) {
        try {
            if (typeface == null) {
                typeface = Typeface.createFromAsset(ctx.getAssets(),
                        getResources().getString(R.string.app_font1));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        setTypeface(typeface);
        return true;
    }   
}

In String.xml

Add this tag-

    <string name="app_font1">fonts/Roboto-Regular.ttf</string>

In XML file:

<PackageName.MyTextView
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:gravity="center"
      android:text="Hello" />
Sagar Zala
  • 4,854
  • 9
  • 34
  • 62