Search code examples
javaandroidpublic-method

Make a public type face method in Android


I am trying to apply a custom font in different Activities, right now I have the following code in the onCreate() in my MainActivity:

String fontTitle = "fonts/OpenSans-Bold.ttf";
Typeface titleFont = Typeface.createFromAsset(getAssets(), fontTitle);
page_title.setTypeface(titleFont);

I want to know if it is possible to make the Typeface public so I can access it in other activities.

I created a class called FontHelper:

public class FontHelper extends MainActivity {

    // path for the fonts
    String fontTitle = "fonts/OpenSans-Bold.ttf";

    Typeface titleFont = Typeface.createFromAsset(getAssets(), fontTitle);

}

but in other Activities when I use textView.setTypeface(FontHelper.titleFont) I get an error. How can I fix this error?


Solution

  • You can use a static factory method to create your Typeface instance for each Activity like this:

    public class FontHelper {
    
        private static final String FONT_PATH = "fonts/OpenSans-Bold.ttf";
    
        public static Typeface getCustomTypeFace(Context context) {
            return Typeface.createFromAsset(context.getAssets(), FONT_PATH);
        }
    }
    

    You can use it like this:

    public class ExampleActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            final Typeface typeface = FontHelper.getCustomTypeFace(this);
            ...
        }
    }