Arnold Laishram
Arnold Laishram

Reputation: 1881

How to support custom locale font which is not there in Android default Locale

I am trying to build a simple app for localisation of a locale language

"Meitei mayek" of Manipur, India

which is not in the Android locale list.

I have the .ttf file.

How do i do it?

Upvotes: 1

Views: 385

Answers (2)

Farhad
Farhad

Reputation: 13006

You can create a custom TextView to support the custom font for displaying text. Try :

1- Place the .ttf font file in the assets folder of your project.

2- Create a class to extend TextView

public class TextViewIndian extends AppCompatTextView {

public TextViewIndian(Context context) {
    super(context);
    setTypeface(FontFactory.getInstance(context).getMyFont());
}

public TextViewIndian(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setTypeface(FontFactory.getInstance(context).getMyFont());
}
public TextViewIndian(Context context, AttributeSet attrs) {
    super(context, attrs);
    setTypeface(FontFactory.getInstance(context).getMyFont());
}

}

As seen above you need to creare another class called FontFactory to load the font files from assets, in a singleton way to avoid memory leaks.

public class FontFactory {

private static Typeface MYFONT;

private static FontFactory instance ;

private FontFactory(Context context){
    MYFONT = Typeface.createFromAsset(context.getAssets(),"font.ttf");
}

public static FontFactory getInstance(Context context){
    if(instance == null)
        instance = new FontFactory(context);
    return instance ;
}

public Typeface getMyFont(){

    return MYFONT;
}

}

You can use this same approach for other widgets like Button and EditText to create custom ones for your language.

Now you can place this TextViewIndian in your layout.xml files and use them the way you use any other widget and it automatically sets the custom font for its text.

Upvotes: 0

urveshpatel50
urveshpatel50

Reputation: 1685

  1. Create fonts directory under assets and put .ttf file in fonts.

    assets/fonts
    
  2. Use below code whenever you want to set.

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);
    

Upvotes: 1

Related Questions