Reputation: 1881
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
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
Reputation: 1685
Create fonts directory under assets and put .ttf file in fonts.
assets/fonts
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