Related
I'm new in android working on an app that gives the user info about all font's of Google.
For that, I need to make an app with a TextView Something like this
On click of the TextView, the font will change With text.
I'm thinking about using onclicklistener
you can put "your_font.ttf" file in asset folder then import it with
Typeface custom_font_1 = Typeface.createFromAsset(getAssets(), "your_font.ttf");
then assign it to your showCaseTextView with this
showCaseTextView.setTypeFace(custom_font_1);
then in your onClickListener of showCaseTextView to change your specifiedTextView font do like this
specifiedTextView.setTypeFace(custom_font_1);
and repeat it for other fonts.
You can implement your own custom font with TextView, EditText, Button etc.. by using android attributes.
How to
-Here are some steps to use:
1.Create attribute file (res->values->attrs.xml)
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="TextElement">
<attr name="font" format="string"/>
<attr name="underline" format="boolean"/>
</declare-styleable>
</resources>
2.Create Custom TextView class (anywhere in java folder)
3. Use attributes inside your layout file
4. and just run your code.
Here is the full example of your question, you can go through this exmaple:
Full Demonstration
Have 2 way to archive this
1st way
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
This caches the fonts while minimizing the number of accesses to the assets. Now, since we've a method to access our custom font, let's implement a class, which extends TextView.
Extending TextView
Next, we'll create a new Java class, which extends TextView. This allows us to use that class in all XML views. It inherits all functionality and properties of a regular TextView; but adds our custom font.
Once again, we're taking a peek at the source code of our eat foody project. The code might look complex for a second, but is straight-forward:
public class EatFoodyTextView extends TextView {
public EatFoodyTextView(Context context) {
super(context);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
setTypeface(customFont);
}
}
The first three methods are just constructors, which we override to call a single method applyCustomFont(). That method is the important piece of the puzzle. It simply gets the (hopefully cached) font from our FontCache class. Lastly, we've to call setTypeface() with the font and we're almost done. In case you're wondering, we can call the setTypeface() directly (and not on a TextView object), since we're extending the TextView class.
Using the Class
You might wonder, if so much preparation is worth the effort. In this section you'll see that it is indeed. Because all you've left to do is use the class in an XML view and it automatically has your custom font. There is no Java code necessary!
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.futurestudio.foody.views.EatFoodyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
As you can see, you can continue to use all niceties (e.g. textSize, textColor) of TextView. Now, just replace all elements with the class we just created, for example and you applied your custom font everywhere!
(Ref: https://futurestud.io/tutorials/custom-fonts-on-android-extending-textview)
2nd way
Follow Google guide support from API 26 (Android 8) https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
Make change between textview to change font
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textview_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
<com.futurestudio.foody.views.EatFoodyTextView
android:id="#+id/textview_custom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:visibility="gone"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
attention at android:visibility="gone"
in Activity you use this code to toggle between 2 TextViews
final TextView normalTextView = findViewById(R.id.textview_normal);
final TextView customTextView = findViewById(R.id.textview_custom);
normalTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.GONE);
customTextView.setVisibility(View.VISIBLE);
}
});
customTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.VISIBLE);
customTextView.setVisibility(View.GONE);
}
});
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 change the font in a TextView, as default it's shown up as Arial? How to change it to Helvetica?
First, the default is not Arial. The default is Droid Sans.
Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java.
Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans), Droid Sans Mono (monospace), and Droid Serif (serif). While you can bundle your own fonts with your application and use them via setTypeface(), bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).
EDIT
The Android design language relies on traditional typographic tools
such as scale, space, rhythm, and alignment with an underlying grid.
Successful deployment of these tools is essential to help users
quickly understand a screen of information. To support such use of
typography, Ice Cream Sandwich introduced a new type family named
Roboto, created specifically for the requirements of UI and
high-resolution screens.
The current TextView framework offers Roboto in thin, light, regular
and bold weights, along with an italic style for each weight. The
framework also offers the Roboto Condensed variant in regular and bold
weights, along with an italic style for each weight.
After ICS, android includes Roboto fonts style,
Read more Roboto
EDIT 2
With the advent of Support Library 26, Android now supports custom fonts by
default. You can insert new fonts in res/fonts which can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here
First download the .ttf file of the font you need (arial.ttf). Place it in the assets folder. (Inside assets folder create new folder named fonts and place it inside it.) Use the following code to apply the font to your TextView:
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/DroidSansFallback.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);
You might want to create static class which will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance.
Just make sure that you create a sub-folder called "fonts" under "assets" folder.
Do something like:
public class CustomFontsLoader {
public static final int FONT_NAME_1 = 0;
public static final int FONT_NAME_2 = 1;
public static final int FONT_NAME_3 = 2;
private static final int NUM_OF_CUSTOM_FONTS = 3;
private static boolean fontsLoaded = false;
private static Typeface[] fonts = new Typeface[3];
private static String[] fontPath = {
"fonts/FONT_NAME_1.ttf",
"fonts/FONT_NAME_2.ttf",
"fonts/FONT_NAME_3.ttf"
};
/**
* Returns a loaded custom font based on it's identifier.
*
* #param context - the current context
* #param fontIdentifier = the identifier of the requested font
*
* #return Typeface object of the requested font.
*/
public static Typeface getTypeface(Context context, int fontIdentifier) {
if (!fontsLoaded) {
loadFonts(context);
}
return fonts[fontIdentifier];
}
private static void loadFonts(Context context) {
for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
}
fontsLoaded = true;
}
}
This way, you can get the font from everywhere in your application.
Best practice ever
TextViewPlus.java:
public class TextViewPlus extends TextView {
private static final String TAG = "TextView";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(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.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
attrs.xml: (Where to place res/values)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
How to use:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.mypackage.TextViewPlus
android:id="#+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="#string/showingOffTheNewTypeface"
foo:customFont="my_font_name_regular.otf">
</com.mypackage.TextViewPlus>
</LinearLayout>
Hope this will help you.
The answers above are correct. Just make sure that you create a sub-folder called "fonts" under "assets" folder if you are using that piece of code.
Another way to consolidate font creation...
public class Font {
public static final Font PROXIMA_NOVA = new Font("ProximaNovaRegular.otf");
public static final Font FRANKLIN_GOTHIC = new Font("FranklinGothicURWBoo.ttf");
private final String assetName;
private volatile Typeface typeface;
private Font(String assetName) {
this.assetName = assetName;
}
public void apply(Context context, TextView textView) {
if (typeface == null) {
synchronized (this) {
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), assetName);
}
}
}
textView.setTypeface(typeface);
}
}
And then to use in your activity...
myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);
Mind you, this double-checked locking idiom with the volatile field only works correctly with the memory model used in Java 1.5+.
Best practice is to use Android Support Library version 26.0.0 or above.
STEP 1: add font file
In res folder create new font resource dictionary
Add font file (.ttf, .orf)
For example, when font file will be helvetica_neue.ttf that will generates R.font.helvetica_neue
STEP 2: create font family
In font folder add new resource file
Enclose each font file, style, and weight attribute in the element.
For example:
<?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/helvetica_neue" />
</font-family>
STEP 3: use it
In xml layouts:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/my_font"/>
Or add fonts to style:
<style name="customfontstyle" parent="#android:style/TextAppearance.Small">
<item name="android:fontFamily">#font/lobster</item>
</style>
For more examples you can follow documentation:
Working with fonts
When your font is stored inside res/asset/fonts/Helvetica.ttf use the following:
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf");
txt.setTypeface(tf);
Or, if your font file is stores inside res/font/helvetica.ttf use the following:
Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.
import android.content.Context;
import android.graphics.Typeface;
public enum FontLoader {
ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");
private final String name;
private Typeface typeFace;
private FontLoader(final String name) {
this.name = name;
typeFace=null;
}
public static Typeface getTypeFace(Context context,String name){
try {
FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
if(item.typeFace==null){
item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");
}
return item.typeFace;
} catch (Exception e) {
return null;
}
}
public static Typeface getTypeFace(Context context,int id){
FontLoader myArray[]= FontLoader.values();
if(!(id<myArray.length)){
return null;
}
try {
if(myArray[id].typeFace==null){
myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");
}
return myArray[id].typeFace;
}catch (Exception e) {
return null;
}
}
public static Typeface getTypeFaceByName(Context context,String name){
for(FontLoader item: FontLoader.values()){
if(name.equalsIgnoreCase(item.name)){
if(item.typeFace==null){
try{
item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");
}catch (Exception e) {
return null;
}
}
return item.typeFace;
}
}
return null;
}
public static void loadAllFonts(Context context){
for(FontLoader item: FontLoader.values()){
if(item.typeFace==null){
try{
item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");
}catch (Exception e) {
item.typeFace=null;
}
}
}
}
}
Then just use this code on you textview:
Typeface typeFace=FontLoader.getTypeFace(context,"arial");
if(typeFace!=null) myTextView.setTypeface(typeFace);
I finally got a very easy solution to this.
use these Support libraries in app level gradle,
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.0.2'
then create a directory named "font" inside the res folder
put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
After that, reference that font from xml like this
<Button
android:id="#+id/btn_choose_employee"
android:layout_width="140dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:background="#drawable/rounded_red_btn"
android:onClick="btnEmployeeClickedAction"
android:text="#string/searching_jobs"
android:textAllCaps="false"
android:textColor="#color/white"
android:fontFamily="#font/times_new_roman_test"
/>
In this example, times_new_roman_test is a font ttf file from that font directory
import java.lang.ref.WeakReference;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
public class FontsManager {
private static FontsManager instance;
private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();
private static Context context;
private FontsManager(final Context ctx) {
if (context == null) {
context = ctx;
}
}
public static FontsManager getInstance(final Context appContext) {
if (instance == null) {
instance = new FontsManager(appContext);
}
return instance;
}
public static FontsManager getInstance() {
if (instance == null) {
throw new RuntimeException(
"Call getInstance(Context context) at least once to init the singleton properly");
}
return instance;
}
public Typeface getFont(final String assetName) {
final WeakReference<Typeface> tfReference = typefaces.get(assetName);
if (tfReference == null || tfReference.get() == null) {
final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
assetName);
typefaces.put(assetName, new WeakReference<Typeface>(tf));
return tf;
}
return tfReference.get();
}
}
This way, you can create a View which inherits from TextView and calls setTypeface on its constructor.
get font from asset and set to all children
public static void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView ) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
}
} catch (Exception e) {
}
}
add class FontTextView.java:
public class FontTextView extends TextView {
String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
init(attrs);
}
}
public FontTextView(Context context) {
super(context);
if (!isInEditMode()) {
init(null);
}
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
if (a.getString(R.styleable.FontTextView_font_type) != null) {
String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];
if (fontName != null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
}
add to assets library font
add to attrs.xml ,
The numbers should be in the order in array class.
<declare-styleable name="FontTextView">
<attr name="font_type" format="enum">
<enum name="HelveticaNeue" value="0"/>
<enum name="HelveticaNeueLight" value="1"/>
<enum name="motschcc" value="2"/>
<enum name="symbol" value="3"/>
</attr>
Select a font from the list
Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.
Check below link to check roboto fonts:
How to use Roboto in xml layout
Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
......
<item name="android:buttonStyle">#style/MyButton</item>
<item name="android:textViewStyle">#style/MyTextView</item>
</style>
<style name="MyButton" parent="#style/Widget.AppCompat.Button">
<item name="android:textAllCaps">false</item>
<item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="MyTextView" parent="#style/TextAppearance.AppCompat">
<item name="android:fontFamily">sans-serif-light</item>
</style>
And don't forget to use 'AppTheme' in your AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
......
</application>
Maybe something a bit simpler:
public class Fonts {
public static HashSet<String,Typeface> fonts = new HashSet<>();
public static Typeface get(Context context, String file) {
if (! fonts.contains(file)) {
synchronized (this) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
fonts.put(name, typeface);
}
}
return fonts.get(file);
}
}
// Usage
Typeface myFont = Fonts.get("arial.ttf");
(Note this code is untested, but in general this approach should work well.)
I am trying to do a application-wide font change and creating a style file to do so. In this file (below) I just want to change typeface value of TextAppearance style of Android.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NightRiderFont" parent="#android:style/TextAppearance">
<item name="android:typeface"> /***help need here***/ </item>
</style>
</resources>
However font is in "assets/fonts/". How can I access this font, so I can use that style as a theme to get rid of changing all TextViews by hand programatically.
As summary: How can I access 'a file from assets folder' in XML?
In my research, there is no way to add external font to the xml file. Only the 3 default font is available in xml
But you can use in java using this code.
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");
textfield.setTypeface(tf,Typeface.BOLD);
Update:
Now I find a way to do this by creating a custom class extending the TextView and use that in the xml file.
public class TextViewWithFont extends TextView {
private int defaultDimension = 0;
private int TYPE_BOLD = 1;
private int TYPE_ITALIC = 2;
private int FONT_ARIAL = 1;
private int FONT_OPEN_SANS = 2;
private int fontType;
private int fontName;
public TextViewWithFont(Context context) {
super(context);
init(null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.font, defStyle, 0);
fontName = a.getInt(R.styleable.font_name, defaultDimension);
fontType = a.getInt(R.styleable.font_type, defaultDimension);
a.recycle();
MyApplication application = (MyApplication ) getContext().getApplicationContext();
if (fontName == FONT_ARIAL) {
setFontType(application .getArialFont());
} else if (fontName == FONT_OPEN_SANS) {
setFontType(application .getOpenSans());
}
}
private void setFontType(Typeface font) {
if (fontType == TYPE_BOLD) {
setTypeface(font, Typeface.BOLD);
} else if (fontType == TYPE_ITALIC) {
setTypeface(font, Typeface.ITALIC);
} else {
setTypeface(font);
}
}
}
and in xml
<com.example.customwidgets.TextViewWithFont
font:name="Arial"
font:type="bold"
android:layout_width="wrap_content"
android:text="Hello world "
android:padding="5dp"
android:layout_height="wrap_content"/>
dont forget to add the schema in root of your xml
xmlns:font="http://schemas.android.com/apk/res-auto"
And create an attrs.xml file inside values directory, which is holding our custom attribues:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="font">
<attr name="type">
<enum name="bold" value="1"/>
<enum name="italic" value="2"/>
</attr>
<attr name="name">
<enum name="Arial" value="1"/>
<enum name="OpenSans" value="2"/>
</attr>
</declare-styleable>
</resources>
Update:
Found some performance issue when this custom view is used in
listview, that is because the font Object is creating every time the
view is loaded. Solution I found is to initialize the font in Application
Class and refer that font object by
MyApplication application = (MyApplication) getContext().getApplicationContext();
Application class will look like this
public class MyApplication extends Application {
private Typeface arialFont, openSans;
public void onCreate() {
super.onCreate();
arialFont = Typeface.createFromAsset(getAssets(), QRUtils.FONT_ARIAL);
openSans = Typeface.createFromAsset(getAssets(), QRUtils.FONT_OPEN_SANS);
}
public Typeface getArialFont() {
return arialFont;
}
public Typeface getOpenSans() {
return openSans;
}
}
Edit 2:
Finally fonts are supported by xml (also backwards compatible via support library): https://developer.android.com/preview/features/fonts-in-xml.html
Edit:
I now use the Calligraphy library . It is the easiest way for custom fonts.
What can you do:
Custom font in a TextView
Custom font in TextAppearance
Custom font in Styles
Custom font in Themes
FontSpannable to only apply font to a part of the text
I found another way to do this.
You have to make your own TextView using this tutorial
It is not that difficult and after this you can just use that TextView with your own font.
I don't know if anybody still watches this, but I thought it might help.
Uses this function if you are using single font.
public static void applyFont(final Context context, final View root, final String fontName) {
try {
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
for (int i = 0; i < viewGroup.getChildCount(); i++)
applyFont(context, viewGroup.getChildAt(i), fontName);
} else if (root instanceof TextView)
((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName));
} catch (Exception e) {
Log.e("ProjectName", String.format("Error occured when trying to apply %s font for %s view", fontName, root));
e.printStackTrace();
}
}
Soorya is right, but if you have to put the same font on many textViews, I recommend you to put that code inside a static method that return the Typeface wanted. It will reduce lines in your code. Or even better create a class that extends Application and make a GET method that return the Typeface. That method will be reachable from any Activity inside your application (without the need of using static variables or static methods).
Check this out with the help of this don't need to set custom font programmatically.
https://stackoverflow.com/a/27588966/4331353
fount change is very basic functionality in android which is mostly needed to each and every application.so every one want to change only once in application that reduce our development time so i would suggest you to see this link
FountChanger.class.
You Have just make Public calls And attached Method like this
public class TextViewFontType {
public Typeface typeface;
public void fontTextView(final TextView textView, final String fonttype) {
typeface = Typeface.createFromAsset(textView.getContext().getAssets(), fonttype);
textView.setTypeface(typeface);
}
have you use any where method TextView set font-family.
public class FontList {
public static final String gothicbNormal="fonts/gothicb.ttf";
public static final String gothicbBold="fonts/gothicb.ttf";
}
made FontList calss after you have just call methods any where with pass two parameter.
I took droid kid's answer and made it work with ANY font, just by typing the font filename directly into the XML:
layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto" >
<!-- where font file is at "assets/fonts/arial.ttf" -->
<com.odbol.widgets.TextViewWithFont
...
custom:fontFilePath="fonts/arial.ttf" />
</RelativeLayout>
Fonts.java
public class Fonts {
// use Weak so fonts are freed from memory when you stop using them
private final static Map<String, Typeface> fonts = new WeakHashMap<>(5);
/***
* Returns a font at the given path within the assets directory.
*
* Caches fonts to save resources.
*
* #param context
* #param fontPath Path to a font file relative to the assets directory, e.g. "fonts/Arial.ttf"
* #return
*/
public synchronized static Typeface getFont(Context context, String fontPath) {
Typeface font = fonts.get(fontPath);
if (font == null) {
font = Typeface.createFromAsset(context.getAssets(), fontPath);
fonts.put(fontPath, font);
}
return font;
}
}
values/attrs.xml
<resources>
<declare-styleable name="TextViewWithFont">
<!-- a path to a font, relative to the assets directory -->
<attr name="fontFilePath" format="string" />
<attr name="type">
<enum name="bold" value="1"/>
<enum name="italic" value="2"/>
</attr>
</declare-styleable>
</resources>
TextViewWithFont.java
public class TextViewWithFont extends TextView {
private int defaultDimension = 0;
private int TYPE_BOLD = 1;
private int TYPE_ITALIC = 2;
private int fontType;
private int fontName;
public TextViewWithFont(Context context) {
super(context);
init(null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.TextViewWithFont, defStyle, 0);
String fontPath = a.getString(R.styleable.TextViewWithFont_fontFilePath);
fontType = a.getInt(R.styleable.TextViewWithFont_type, defaultDimension);
a.recycle();
if (fontPath != null) {
setFontType(Fonts.getFont(getContext(), fontPath));
}
}
private void setFontType(Typeface font) {
if (fontType == TYPE_BOLD) {
setTypeface(font, Typeface.BOLD);
} else if (fontType == TYPE_ITALIC) {
setTypeface(font, Typeface.ITALIC);
} else {
setTypeface(font);
}
}
}
hope use full to you:-
TextView text = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf");
text.setTypeface(font);
Instead of assets folder, you can put the .ttf file on fonts folder.
To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+.
Right click res folder, new -> Android resource directory-> select font -> Ok.
put your "myfont.ttf" file in newly created font folder.
On res/values/styles.xml
add,
<style name="customfontstyle" parent="#android:style/TextAppearance.Small">
<item name="android:fontFamily">#font/myfont</item>
</style>
On layout file add android:textAppearance="#style/customfontstyle",
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/customfontstyle"/>
Refer : https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
//accessing font file in code,
Typeface type = Typeface.createFromAsset(getResources().getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);//assign typeface to textview
//in assets folder->fonts(foldername)->arial.ttf(font file name)
You can use this library: https://github.com/InflationX/Calligraphy
You only have to add the font you want to use on your layout.
Like this:
<TextView
fontPath="fonts/verdana.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
1.Fisrt we can add assets folder> in that your font styles.ttfs in your app then
2.write access code for fonts in strings like :
<string name="fontregular">OpenSans-Light.ttf</string>
<string name="fontmedium">OpenSans-Regular.ttf</string>
3.Accessing some layout xml file textview code like this below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#string/fontregular"
android:textColor="#color/normalfont"
android:textSize="#dimen/textregular"/>
4.Add dimensions for font size :
<dimen name="textregular">14sp</dimen>
<dimen name="textheader">16sp</dimen>
<dimen name="smalltext">12sp</dimen>
<dimen name="littletext">10sp</dimen>
<dimen name="hightfont">18sp</dimen>
5.Add font color in colors :
<color name="normalfont">#666</color>
<color name="headerfont">#333</color>
<color name="aquablue">#4da8e3</color>
<color name="orange">#e96125</color>
6.Then apply changes it is easy process to change hole app.
Happy coding keep smile..
You can access your font file from assets folder to xml file.
android:fontFamily="fonts/roboto_regular.ttf"
fonts is the sub folder in assets folder.
How to change the font in a TextView, as default it's shown up as Arial? How to change it to Helvetica?
First, the default is not Arial. The default is Droid Sans.
Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java.
Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans), Droid Sans Mono (monospace), and Droid Serif (serif). While you can bundle your own fonts with your application and use them via setTypeface(), bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).
EDIT
The Android design language relies on traditional typographic tools
such as scale, space, rhythm, and alignment with an underlying grid.
Successful deployment of these tools is essential to help users
quickly understand a screen of information. To support such use of
typography, Ice Cream Sandwich introduced a new type family named
Roboto, created specifically for the requirements of UI and
high-resolution screens.
The current TextView framework offers Roboto in thin, light, regular
and bold weights, along with an italic style for each weight. The
framework also offers the Roboto Condensed variant in regular and bold
weights, along with an italic style for each weight.
After ICS, android includes Roboto fonts style,
Read more Roboto
EDIT 2
With the advent of Support Library 26, Android now supports custom fonts by
default. You can insert new fonts in res/fonts which can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here
First download the .ttf file of the font you need (arial.ttf). Place it in the assets folder. (Inside assets folder create new folder named fonts and place it inside it.) Use the following code to apply the font to your TextView:
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/DroidSansFallback.ttf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);
You might want to create static class which will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance.
Just make sure that you create a sub-folder called "fonts" under "assets" folder.
Do something like:
public class CustomFontsLoader {
public static final int FONT_NAME_1 = 0;
public static final int FONT_NAME_2 = 1;
public static final int FONT_NAME_3 = 2;
private static final int NUM_OF_CUSTOM_FONTS = 3;
private static boolean fontsLoaded = false;
private static Typeface[] fonts = new Typeface[3];
private static String[] fontPath = {
"fonts/FONT_NAME_1.ttf",
"fonts/FONT_NAME_2.ttf",
"fonts/FONT_NAME_3.ttf"
};
/**
* Returns a loaded custom font based on it's identifier.
*
* #param context - the current context
* #param fontIdentifier = the identifier of the requested font
*
* #return Typeface object of the requested font.
*/
public static Typeface getTypeface(Context context, int fontIdentifier) {
if (!fontsLoaded) {
loadFonts(context);
}
return fonts[fontIdentifier];
}
private static void loadFonts(Context context) {
for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
}
fontsLoaded = true;
}
}
This way, you can get the font from everywhere in your application.
Best practice ever
TextViewPlus.java:
public class TextViewPlus extends TextView {
private static final String TAG = "TextView";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(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.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
attrs.xml: (Where to place res/values)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
How to use:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.mypackage.TextViewPlus
android:id="#+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="#string/showingOffTheNewTypeface"
foo:customFont="my_font_name_regular.otf">
</com.mypackage.TextViewPlus>
</LinearLayout>
Hope this will help you.
The answers above are correct. Just make sure that you create a sub-folder called "fonts" under "assets" folder if you are using that piece of code.
Another way to consolidate font creation...
public class Font {
public static final Font PROXIMA_NOVA = new Font("ProximaNovaRegular.otf");
public static final Font FRANKLIN_GOTHIC = new Font("FranklinGothicURWBoo.ttf");
private final String assetName;
private volatile Typeface typeface;
private Font(String assetName) {
this.assetName = assetName;
}
public void apply(Context context, TextView textView) {
if (typeface == null) {
synchronized (this) {
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), assetName);
}
}
}
textView.setTypeface(typeface);
}
}
And then to use in your activity...
myTextView = (TextView) findViewById(R.id.myTextView);
Font.PROXIMA_NOVA.apply(this, myTextView);
Mind you, this double-checked locking idiom with the volatile field only works correctly with the memory model used in Java 1.5+.
Best practice is to use Android Support Library version 26.0.0 or above.
STEP 1: add font file
In res folder create new font resource dictionary
Add font file (.ttf, .orf)
For example, when font file will be helvetica_neue.ttf that will generates R.font.helvetica_neue
STEP 2: create font family
In font folder add new resource file
Enclose each font file, style, and weight attribute in the element.
For example:
<?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/helvetica_neue" />
</font-family>
STEP 3: use it
In xml layouts:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/my_font"/>
Or add fonts to style:
<style name="customfontstyle" parent="#android:style/TextAppearance.Small">
<item name="android:fontFamily">#font/lobster</item>
</style>
For more examples you can follow documentation:
Working with fonts
When your font is stored inside res/asset/fonts/Helvetica.ttf use the following:
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf");
txt.setTypeface(tf);
Or, if your font file is stores inside res/font/helvetica.ttf use the following:
Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.
import android.content.Context;
import android.graphics.Typeface;
public enum FontLoader {
ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");
private final String name;
private Typeface typeFace;
private FontLoader(final String name) {
this.name = name;
typeFace=null;
}
public static Typeface getTypeFace(Context context,String name){
try {
FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
if(item.typeFace==null){
item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");
}
return item.typeFace;
} catch (Exception e) {
return null;
}
}
public static Typeface getTypeFace(Context context,int id){
FontLoader myArray[]= FontLoader.values();
if(!(id<myArray.length)){
return null;
}
try {
if(myArray[id].typeFace==null){
myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");
}
return myArray[id].typeFace;
}catch (Exception e) {
return null;
}
}
public static Typeface getTypeFaceByName(Context context,String name){
for(FontLoader item: FontLoader.values()){
if(name.equalsIgnoreCase(item.name)){
if(item.typeFace==null){
try{
item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");
}catch (Exception e) {
return null;
}
}
return item.typeFace;
}
}
return null;
}
public static void loadAllFonts(Context context){
for(FontLoader item: FontLoader.values()){
if(item.typeFace==null){
try{
item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");
}catch (Exception e) {
item.typeFace=null;
}
}
}
}
}
Then just use this code on you textview:
Typeface typeFace=FontLoader.getTypeFace(context,"arial");
if(typeFace!=null) myTextView.setTypeface(typeFace);
I finally got a very easy solution to this.
use these Support libraries in app level gradle,
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.0.2'
then create a directory named "font" inside the res folder
put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
After that, reference that font from xml like this
<Button
android:id="#+id/btn_choose_employee"
android:layout_width="140dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:background="#drawable/rounded_red_btn"
android:onClick="btnEmployeeClickedAction"
android:text="#string/searching_jobs"
android:textAllCaps="false"
android:textColor="#color/white"
android:fontFamily="#font/times_new_roman_test"
/>
In this example, times_new_roman_test is a font ttf file from that font directory
import java.lang.ref.WeakReference;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
public class FontsManager {
private static FontsManager instance;
private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();
private static Context context;
private FontsManager(final Context ctx) {
if (context == null) {
context = ctx;
}
}
public static FontsManager getInstance(final Context appContext) {
if (instance == null) {
instance = new FontsManager(appContext);
}
return instance;
}
public static FontsManager getInstance() {
if (instance == null) {
throw new RuntimeException(
"Call getInstance(Context context) at least once to init the singleton properly");
}
return instance;
}
public Typeface getFont(final String assetName) {
final WeakReference<Typeface> tfReference = typefaces.get(assetName);
if (tfReference == null || tfReference.get() == null) {
final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
assetName);
typefaces.put(assetName, new WeakReference<Typeface>(tf));
return tf;
}
return tfReference.get();
}
}
This way, you can create a View which inherits from TextView and calls setTypeface on its constructor.
get font from asset and set to all children
public static void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView ) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
}
} catch (Exception e) {
}
}
add class FontTextView.java:
public class FontTextView extends TextView {
String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
init(attrs);
}
}
public FontTextView(Context context) {
super(context);
if (!isInEditMode()) {
init(null);
}
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
if (a.getString(R.styleable.FontTextView_font_type) != null) {
String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];
if (fontName != null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
}
add to assets library font
add to attrs.xml ,
The numbers should be in the order in array class.
<declare-styleable name="FontTextView">
<attr name="font_type" format="enum">
<enum name="HelveticaNeue" value="0"/>
<enum name="HelveticaNeueLight" value="1"/>
<enum name="motschcc" value="2"/>
<enum name="symbol" value="3"/>
</attr>
Select a font from the list
Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.
Check below link to check roboto fonts:
How to use Roboto in xml layout
Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
......
<item name="android:buttonStyle">#style/MyButton</item>
<item name="android:textViewStyle">#style/MyTextView</item>
</style>
<style name="MyButton" parent="#style/Widget.AppCompat.Button">
<item name="android:textAllCaps">false</item>
<item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="MyTextView" parent="#style/TextAppearance.AppCompat">
<item name="android:fontFamily">sans-serif-light</item>
</style>
And don't forget to use 'AppTheme' in your AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
......
</application>
Maybe something a bit simpler:
public class Fonts {
public static HashSet<String,Typeface> fonts = new HashSet<>();
public static Typeface get(Context context, String file) {
if (! fonts.contains(file)) {
synchronized (this) {
Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
fonts.put(name, typeface);
}
}
return fonts.get(file);
}
}
// Usage
Typeface myFont = Fonts.get("arial.ttf");
(Note this code is untested, but in general this approach should work well.)