This question already has answers here:
Android - Using Custom Font
(21 answers)
Closed 3 years ago.
I would like to know if it is possible to set a fontFamily variable in Android Studio like you can do with Strings.
I don't want to do anything fancy like custom fonts. I just want to have the convenience of being able to change the fontFamily of every textView at once.
So far I was not able to find a font tag. I hope that some of you can help me.
Best regards and thanks in advance :)
Make a Custom TextView Class and use it in textview
public class MetaFont extends TextView {
public MetaFont(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
a(attributeSet);
}
public MetaFont(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
a(attributeSet);
}
public MetaFont(Context context) {
super(context);
a(null);
}
private void a(AttributeSet attributeSet) {
if (attributeSet != null) {
TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attributeSet, ATTRS);
setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Comfortaa.ttf"));
obtainStyledAttributes.recycle();
}
}
}
Put the font otf file to /assets/fonts, create a utils for dealing with fonts like:
public class TypefaceUtils {
private static Typeface myFont1;
private static Typeface myFont2;
public static Typeface getMyFont1() {
return myFont1;
}
public static Typeface getMyFont2() {
return myFont2;
}
public static void initTypeface(Context context) {
if (context != null) {
myFont1 = Typeface.createFromAsset(context.getAssets(), "fonts/myfont1.otf");
myFont2 = Typeface.createFromAsset(context.getAssets(), "fonts/myfont2.otf");
}
}
}
Init fonts when onCreate your MainAcitivity
TypefaceUtils.initTypeface(this);
Set the font where you need, like:
textView.setTypeface(TypefaceUtils.getMyFont1());
Related
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?
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);
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.
I am developing an Android app. In my app, I am using multiple languages. Totally I am localizing. But I am having a problem with it. Currently, my app will support two languages. But my problem is I want to change the typeface for all TextView, EditText, Button and so on when the user change the language.
This is how I am setting typeface programmatically when the language change:
if(Language=="mm")
{
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/tharlon.ttf");
icBtnFindPlaces.setTypeface(tf);
}
else{
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/inconsolata.ttf");
icBtnFindPlaces.setTypeface(tf);
}
As you can see above I have do it for every views with text. This is not a good way. Why I want is I want to set typeface globally for all views, not one by one. Is it possible?
Hi here is a good example.
If there are many TextViews whose external font need to be set, then you have to create a your own custom TextView and set the font like as below:
Add FontManager as a Singleton Java class
public class FontManager {
public static Typeface light;
public static Typeface medium;
public static Typeface regular;
private static FontManager instance;
private AssetManager mgr;
private FontManager(AssetManager _mgr) {
this.mgr = _mgr;
lght = Typeface.createFromAsset(mgr,"---.ttf");
medium = Typeface.createFromAsset(mgr,"---.ttf");
regular = Typeface.createFromAsset(mgr,"---.ttf");
}
public static FontManager init(AssetManager mgr) {
if(instance != null)
return instance;
return instance = new FontManager(mgr);
}
public static FontManager getInstance() {
return instance;
}
private String fixAssetFilename(String asset) {
// Empty font filename?
// Just return it. We can't help.
if (asset.length() == 0)
return asset;
return asset;
}
}
Call it in your Splash Activity as:
FontManager.init(getApplicationContext().getAssets());
public class LightTextView extends TextView {
public LightTextView(Context context) {
super(context);
}
public LightTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if(context.getString(R.string.lang).equals("en"))
setTypeface(FontManager.light);
else
setTypeface(FontManager.medium);
}
}
Add values --> string.xml
<string name="lang">en</string>
values-fr --> string.xml
<string name="lang">fr</string>
<com.exa.fonttest.LightTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:textSize="20sp"
android:textColor="#color/white"
android:text="Good luck"/>
While changing the locale automatically change the font.
Good luck.
I want to change the font of my complete app!
But I don't know how to access the complete application.
I have a way to access a text by Id, how can I change the code to access the whole App?
public class ExternalFont extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String fontPath = "fonts/FreeUniversal-Regular.ttf";
TextView txtUniversal = (TextView) findViewById(R.id.universal);
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
txtUniversal.setTypeface(tf);
}
}
To change all typeface for all TextView in app you should create custom style then add it into AppTheme style.
`<style name="customTextVeiw" parent="Widget.MaterialComponents.TextView">
<item name"fontFamilt">#font/custom_free_universal_regular</item>`
then add this style inside style.xml file inside AppTheme style.
`<style name="AppTheme" parent="AppBaseTheme">
<item name="android:textViewStyle">#style/customTextVeiw</item>`
Unfortunately there is no direct way in which you can change the typeface of all the TextViews you are using in your app by just changing the default typeface.
What you can do is create your own custom TextView and set typeface on it as suggested by #josedlujan. But the flaw in that approach is that each time a TextView object will be created, a new Typeface object will be created which is extremely bad for RAM usage (A Typeface object typically varies from 8-13 kb for typefaces like Roboto). So it is better to cache your Typeface once it has got loaded.
Step 1: Create a Typeface cache for your app -
public enum Font {
// path to your font asset
Y("fonts/Roboto-Regular.ttf");
public final String name;
private Typeface typeface;
Font(String s) {
name = s;
}
public Typeface getTypeface(Context context) {
if (typeface != null) return typeface;
try {
return typeface = Typeface.createFromAsset(context.getAssets(), name);
} catch (Exception e) {
return null;
}
}
public static Font fromName(String fontName) {
return Font.valueOf(fontName.toUpperCase());
}
Step 2: Define your own custom attribute "customFont" in attrs.xml for your CustomTextView
attrs.xml -
<declare-styleable name="CustomFontTextView">
<attr name="customFont"/>
</declare-styleable>
<com.packagename.CustomFontTextView
android:id="#+id/some_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customFont="rl"/>
Step 3: Create your own custom TextView
public class CustomFontTextView extends TextView {
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CustomFontTextView(Context context) {
super(context);
init(context, null);
}
private void init(Context context, AttributeSet attrs) {
if (attrs == null) {
return;
}
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, 0 ,0);
String fontName = a.getString(R.styleable.CustomFontTextView_customFont);
String textStyle = attrs.getAttributeValue(styleScheme, styleAttribute);
if (fontName != null) {
Typeface typeface = Font.fromName(fontName).getTypeface(context);
if (textStyle != null) {
int style = Integer.decode(textStyle);
setTypeface(typeface, style);
} else {
setTypeface(typeface);
}
}
a.recycle();
}
To use Font for all app text you should use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher.
To add fonts as resources, perform the following steps in the Android Studio:
Right-click the res folder and go to New > Android resource directory.
The New Resource Directory window appears.
In the Resource type list, select font, and then click OK.
Add your font files in the font folder like this free_universal_regular.ttf
you should start your font with lower and under score instead of -.
Creating a font family
Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
Enter the file name e.g: custom_free_universal_regular.xml , and then click OK. The new font resource XML opens in the editor.
add this in custom_free_universal_regular.xml file.
<?xml version="1.0" encoding="utf-8"?> <font-family xmlns:android="http://schemas.android.com/apk/res/android"> <font android:fontStyle="normal" android:fontWeight="400" android:font="#font/free_universal_regular" /> </font-family>
Now we can use this font family anywhere in our app like this
For e.g for all app use it inside the style.xml
<style name="BaseTheme" parent=""> <item name="fontFamily">#font/custom_free_universal_regular</item>
or in a specific element use it like this
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="#font/custom_free_universal_regular"/>
I hope that could help.
Create your own Textview with custom style.
Example:
public class YourTextView extends TextView {
public YourTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public YourTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public YourTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"fonts/yourfont.ttf");
setTypeface(tf);
}
}
You can use in yours XML.
How to set different fonts with different locale?
lets assume i am having a string file hi hindi but my phone don't support hindi fonts, how to add fonts from asset as default font though out the application?
To add custom font,Please follow below Steps.
Create a folder named fonts in assets folder.
put your custom font in fonts folder.(You can also put your custom fonts in assets folder).
3.Add below code in your java file
Typeface tfFonts = Typeface.createFromAsset(getAssets(),"fonts/customfont.ttf");
componentName.setTypeface(tfFonts);
First, copy your customized font file (eg custom.ttf) in assets folder.
Then, do like this
1) Add this class OpenHindiFonts.java
import android.content.Context;
import android.graphics.Typeface;
public class OpenHindiFonts {
private static OpenHindiFonts instance;
private static Typeface typeface;
public static OpenHindiFonts getInstance(Context context) {
synchronized (OpenHindiFonts.class) {
if (instance == null) {
instance = new OpenHindiFonts();
typeface = Typeface.createFromAsset(context.getResources().getAssets(), "custom.ttf");
}
return instance;
}
}
public Typeface getTypeFace() {
return typeface;
}
}
2) Add this class - NativelyCustomTextView.
package com.packageName;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class NativelyCustomTextView extends TextView {
public NativelyCustomTextView(Context context) {
super(context);
setTypeface(OpenHindiFonts.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(OpenHindiFonts.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setTypeface(OpenHindiFonts.getInstance(context).getTypeFace());
}
}
3) In your layout xml, need to use this -
<com.packageName.NativelyCustomTextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hindi_text"
android:textColor="#727272"
android:textSize="18dp" />
4) And in your activity code, no need to change anything -
final TextView textV = (TextView) findViewById(...);
textV.setText(getResources().getString(R.string.hindi_text));
#Test limbs:this is what i suggest to you:create all the needed font in the activity by this way :
Typeface tfFonts =Typeface.createFromAsset(getAssets(),"fonts/customfont.ttf");
componentName.setTypeface(tfFonts);
hindi,bangli,what ever you want.create a current Typefacevariable and provide a way to set it dynamically.all what you need than is is to assign all your widget with the font typeface you want.
lefttext.setTypeface((MainActivity.getCurrentTypeface()));
lefttext is the widget you need to set its font.
getCurrentTypeface is a method you create in the main activity to get a reference to the current font.this way you can assign all widget that you need
This question already has answers here:
Using custom font in android TextView using xml
(11 answers)
Closed 9 years ago.
hi there i am newer in android and i want to ask how to use one font for many text views i have use this method
final String DosisPath = "fonts/Dosis-Bold.ttf";
final Typeface Dosis_Bold = Typeface.createFromAsset(getAssets(), DosisPath);
TextView txtCancle = (TextView) findViewById(R.id.cancle);
txtCancle.setTypeface(Dosis_Bold);
and it's work good but i try to make the same Typeface for another TextView but that dosen't work like this
final String DosisPath = "fonts/Dosis-Bold.ttf";
final Typeface Dosis_Bold = Typeface.createFromAsset(getAssets(), DosisPath);
TextView txtCancle = (TextView) findViewById(R.id.cancle);
txtCancle.setTypeface(Dosis_Bold);
EditText ETCode = (EditText)findViewById(R.id.secET);
ETCode.setTypeface(Dosis_Bold);
if the is an error i have done tell me and if there is another way to make that tell me too thanks alot .
This is how you should do it.
Create a class
public class TextViewContent extends TextView {
public TextViewContent(Context context) {
super(context);
setCustomFont(context);
}
public TextViewContent(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context);
}
public TextViewContent(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode()) {
return;
}
setCustomFont(context);
}
private void setCustomFont(Context ctx) {
setTypeface(Typeface.createFromAsset(ctx.getAssets(),
"Champagne_Limousines.ttf"));
}
}
and in your layout file
<com.hardik.test.widget.TextViewContent
style="#style/TextMedium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginTop="5dip"
android:gravity="center"
android:text="#string/tag_line" />
This will display textview in chosen font. Same way for EditText you can extends the EditText class and rest is same.