Custom TrueType font from xml only - android

Is there any way to pass custom font for TextView (or subclasses of it) using only xml without providing any java code like this
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/CustomFont.ttf");

It is not possible to do it purely from XML, but you can create a custom view and reference that from XML. This way you will only need to write the code once, allowing you to recycle it in various layouts.
For instance, declare the class FontTextView:
package com.example;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class FontTextView extends TextView {
/**
* Note that when generating the class from code, you will need
* to call setCustomFont() manually.
*/
public FontTextView(Context context) {
super(context);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(this, attrs);
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(this, attrs);
}
private void setCustomFont(Context context, AttributeSet attrs) {
if (isInEditMode()) {
// Ignore if within Eclipse
return;
}
String font = "myDefaultFont.ttf";
if (attrs != null) {
// Look up any layout-defined attributes
TypedArray a = obtainStyledAttributes(attrs,
R.styleable.FontTextView);
for (int i = 0; i < a.getIndexCount(); i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.FontTextView_customFont:
font = a.getString(attr, 0);
break;
}
}
a.recycle();
}
Typeface tf = null;
try {
tf = Typeface.createFromAsset(getAssets(), font);
} catch (Exception e) {
Log.e("Could not get typeface: " + e.getMessage());
}
setTypeface(tf);
}
}
Define the attribute in res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FontTextView">
<attr name="customFont" format="string" />
</declare-styleable>
</resources>
Use it in a layout:
Declare the namespace:
xmlns:custom="http://schemas.android.com/apk/res/com.example"
Use the FontTextView:
<com.example.FontTextView
android:id="#+id/introduction"
customFont="myCustomFont.ttf"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello world!" />

Related

how to use custom fonts on textview in android

For implementing custom font i seen few examples here issue is different,I am taking custom font in one abstract class which is used in all over the application.i am unable to change the fonts.
thanks in advance.
Create the custom class like below.
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomTextView(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
if (attrs!=null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String fontName = a.getString(R.styleable.CustomTextView_fontName);
if (fontName!=null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/"+fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
and add your font in assets>fonts folder.
add following in attrs.xml
<declare-styleable name="CustomTextView">
<attr name="fontName" format="string" />
</declare-styleable>
to use.
<com.abc.cusomclass.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fontName="/*name of your font from assets/font folder*/"/>
You can do like this.
You have to add your .tff file on the assets folder
ArialMTBoldRegularTextView.java:
public final class ArialMTBoldRegularTextView extends CustomTextView {
public static final String FONT_PATH = "arial-rounded-mt-bold.ttf";
public ArialMTBoldRegularTextView(Context context) {
super(context);
setFont(FONT_PATH);
}
public ArialMTBoldRegularTextView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setFont(FONT_PATH);
}
public ArialMTBoldRegularTextView(Context context, AttributeSet attributeSet, int defStyleAttr) {
super(context, attributeSet, defStyleAttr);
setFont(FONT_PATH);
}
public void setFont(String fontPath) {
changeFont(this, fontPath);
}
public static void changeFont(final CompoundButton button, final String fontPath) {
Typeface typeface = Typeface.createFromAsset(button.getContext().getAssets(), fontPath);
button.setTypeface(typeface);
}
}
CustomTextView.java
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public CustomTextView(Context context, AttributeSet attributeSet, int defStyleAttr) {
super(context, attributeSet, defStyleAttr);
}
public Typeface getFont(final Context context, final String fontPath) {
return Typeface.createFromAsset(context.getAssets(), fontPath);
}
public void changeFont(final TextView textView, final String fontPath) {
Typeface typeface = Typeface.createFromAsset(textView.getContext().getAssets(), fontPath);
textView.setTypeface(typeface);
}
public void changeFont(final CompoundButton button, final String fontPath) {
Typeface typeface = Typeface.createFromAsset(button.getContext().getAssets(), fontPath);
button.setTypeface(typeface);
}
}
and fater in xml:
<packagename.views.ArialMTBoldRegularTextView
android:layout_width="wrap_content"
android:layout_height="35dp"
android:gravity="center"
android:text="Pseudo"/>
try this for custom font fron Assets
// Font path
String fontPath = "fonts/Face Your Fears.ttf";
// text view label
TextView txtGhost = (TextView) findViewById(R.id.ghost);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtGhost.setTypeface(tf);
for more information check this,
http://www.androidhive.info/2012/02/android-using-external-fonts/
now android Support Library 26 supports using fonts directly from your XML see the doc for more details.
The better way of doing this is to make custom TextView with custom font like this:
Java
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class RegularProximaTextView extends TextView {
public static Typeface FONT_NAME;
public RegularProximaTextView(Context context) {
super(context);
if(FONT_NAME == null) FONT_NAME =
Typeface.createFromAsset(context.getAssets(), "fonts/Mark Simonson -
Proxima Nova Regular.otf");
this.setTypeface(FONT_NAME);
}
public RegularProximaTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if(FONT_NAME == null) FONT_NAME =
Typeface.createFromAsset(context.getAssets(), "fonts/Mark Simonson -
Proxima
Nova Regular.otf");
this.setTypeface(FONT_NAME);
}
public RegularProximaTextView(Context context, AttributeSet attrs, int
defStyle) {
super(context, attrs, defStyle);
if(FONT_NAME == null) FONT_NAME =
Typeface.createFromAsset(context.getAssets(), "fonts/Mark Simonson -
Proxima Nova Regular.otf");
this.setTypeface(FONT_NAME);
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:background="#color/colorGreyBar"
>
<com.tracer.joblogic.v2.helpers.custom_ui.RegularProximaTextView
android:id="#+id/tvTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:textColor="#color/colorButtonRed"
android:text="Some text"
android:textSize="8sp"
/>
</android.support.design.widget.CoordinatorLayout>

Custom font in listview Android?

How to add custom font to it?
This is my code:
public void run() {
ListAdapter adapter = new SimpleAdapter(DiaListActivity.this, diaList, R.layout.list_item, new String[]{TAG_SRNO, TAG_NAME}, new int[]{R.id.srno, R.id.name});
setListAdapter(adapter);
}
any help will be appreciated.
In R.layout.list_item layout file if you have any textview then you can set this below code::-
<com.example.TextViewPlus
android:id="#+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="#string/showingOffTheNewTypeface"
foo:customFont="saxmono.ttf">
</com.example.TextViewPlus>
Put these class file into your package:
TextViewPlus.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
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 tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
attrs.xml: (in res/values)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
What I usually do is, create a custom TextView and set it as the view of my contents,
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
} else {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Light.ttf"));
}
}
}
Now simply replace your regular TextView with the Custom one like this,
<TextView
android:id="#+id/R.id.srno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Into,
<com.example.CustomTextView
android:id="#+id/R.id.srno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
This will change the normal TextView with the custom one and hence will add the font.
Note: Make sure you have crated a folder called "fonts" and put the fonts file there.
If can also customize and add different fonts just by adding a single line,
e.g. If you use,
android:textStyle="bold"
It will set the font type Roboto-Regular.ttf. Which is defined here in CustomTextView class,
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
}
Got it...
#Override
public View getView(int pos, View convertView, ViewGroup parent){
View v = convertView;
if(v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
HashMap<String,String> value = diaList.get(pos);
TextView tv = (TextView)v.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(getAssets(), "fonts/oriya.ttf");
tv.setTypeface(custom_fontG);
tv.setText(value.get(TAG_NAME));
TextView tv2 = (TextView)v.findViewById(R.id.srno);
Typeface custom_fontH = Typeface.createFromAsset(getAssets(), "fonts/oriya.ttf");
tv2.setTypeface(custom_fontH);
tv2.setText(value.get(TAG_SRNO));
return v;
}
};
// updating listview
setListAdapter(adapter);

Change color Text from CustomTextView

By default to change textColor programatically is :
textView.setTextColor(Color.RED);
I need to have a custom Textview to change typeface and color by default, How can change textcolor from CustomTextView class, here is my code.
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if(!isInEditMode()) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Lato-Bold.ttf"));
} else if(style == Typeface.ITALIC){ // constant used to set Lato-Light.
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Lato-Light.ttf"));
}else {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Lato-Regular.ttf"));
}
}
}
The below code is the way to set your default text color and typeface.
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
setTypeface(Typeface.createFromAsset(context.getAssets(),"fonts/Lato-Light.ttf"));
setTextColor(Color.RED);
}
}
The init() method gets called every time the text view gets created, and will then set the typeface and color in that. You can manipulate any other variables you want to in there.
Use setTextColor(Color.RED); after each super in each constructor.
Step 1
In the /assets directory (not the /resource directory), create a folder called /fonts. Copy your custom font here. You can use both TTF and OTF fonts.
Step 2
In the /res/values folder, create a new file called attrs.xml. This is how the Android SDK lets you name custom properties for your widgets.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="fontName" format="string" />
</declare-styleable>
</resources>
Step 3
In /res/layouts, you will need to include your to-be-created custom text view in the activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:customfontdemo="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:padding="12dp"
android:text="Standard Android Font" />
<com.authorwjf.customfontdemo.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:padding="12dp"
customfontdemo:fontName="pipe_dream.ttf"
android:text="Custom Android Font" />
</LinearLayout>
Step 4
In the /src folder, you will want to create your MyTextView class. It extends the standard text view, plucks the font name from the custom attribute, and applies the type face.
package com.authorwjf.customfontdemo;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public MyTextView(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
setTextColor(Color.RED);
if (attrs!=null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyTextView);
String fontName = a.getString(R.styleable.MyTextView_fontName);
if (fontName!=null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/"+fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
Step 5
Because the text view is now self-contained, you aren't required to make any modifications to our /src/MainAcitivity.java file.
package com.authorwjf.customfontdemo;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

How to set a particular font for a button text in android?

I want my button text to be in the Copperplate Gothic Light font and I yet have not come across a simple clean code for a simple function as this. Help!
PS: Since android comes with ariel and a few other fonts on its own we need to import (apologies for the lack of a better word since I'm new to this) the font we wish to use. This is all I have been able to gather till yet and this is where the trail ends for me.
If you plan to add the same font to several buttons I suggest that you go all the way and implement it as a style and subclass button:
public class ButtonPlus extends Button {
public ButtonPlus(Context context) {
super(context);
}
public ButtonPlus(Context context, AttributeSet attrs) {
super(context, attrs);
CustomFontHelper.setCustomFont(this, context, attrs);
}
public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
CustomFontHelper.setCustomFont(this, context, attrs);
}
}
This is a helper class to set a font on a TextView (remember, Button is a subclass of TextView) based on the com.my.package:font attribute:
public class CustomFontHelper {
/**
* Sets a font on a textview based on the custom com.my.package:font attribute
* If the custom font attribute isn't found in the attributes nothing happens
* #param textview
* #param context
* #param attrs
*/
public static void setCustomFont(TextView textview, Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFont);
String font = a.getString(R.styleable.CustomFont_font);
setCustomFont(textview, font, context);
a.recycle();
}
/**
* Sets a font on a textview
* #param textview
* #param font
* #param context
*/
public static void setCustomFont(TextView textview, String font, Context context) {
if(font == null) {
return;
}
Typeface tf = FontCache.get(font, context);
if(tf != null) {
textview.setTypeface(tf);
}
}
}
And here's the FontCache to reduce memory usage on older devices:
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
In res/values/attrs.xml we define the custom styleable attribute
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFont">
<attr name="font" format="string"/>
</declare-styleable>
</resources>
And finally an example use in a layout:
<com.my.package.buttons.ButtonPlus
style="#style/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_sometext"/>
And in res/values/style.xml
<style name="button" parent="#android:style/Widget.Button">
<item name="com.my.package:font">fonts/copperplate_gothic_light.TTF</item>
</style>
This may seem like an awful lot of work, but you'll thank me once you have couple of handfuls of buttons and textfields that you want to change font on.
1) Get the font you need as a .ttf (CopperplateGothicLight.ttf for example) file and place it in your project's /assets/ directory
2) Use this code to refer to the font and set it to your button:
Typeface copperplateGothicLight = Typeface.createFromAsset(getAppContext().getAssets(), "CopperplateGothicLight.ttf");
yourButton.setTypeface(copperplateGothicLight);
After several research, my best option was :
public class CustomButton extends Button {
Typeface normalTypeface = FontCache.get("fonts/CopperplateGothicLight.ttf", getContext());
Typeface boldTypeface = FontCache.get("fonts/CopperplateGothicBold.ttf", getContext());
/**
* #param context
*/
public CustomButton(Context context) {
super(context);
}
/**
* #param context
* #param attrs
*/
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* #param context
* #param attrs
* #param defStyleAttr
*/
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
then
Using fontCache from the 1st answer on this : Memory leaks with custom font for set custom font
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
Less code and more usage of the android standards !
MainActivity.java
package com.mehuljoisar.customfontdemo;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button1.setTypeface(Typeface.createFromAsset(getAssets(), "copperplate-gothic-light.ttf"));
button1.setText("hello");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="24dp"
android:text="Button" />
Download link for your desired font:
copperplate_gothic_light
put it inside your asset folder.
Screenshot:
I hope it will be helpful !!
First download TTF file for font style and then put it into the assets folder of your project.
You can set it programmatically by following way :
Typeface font_style = Typeface.createFromAsset(getAssets(), "yourcystomfontstyle.ttf");
yourbutton.setTypeface(font_style);
You can use custom button class as given below.Put your font in asset/font folder.
public class CustomButton extends Button{
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
// TODO Auto-generated constructor stub
}
public CustomButton(Context context) {
super(context);
init();
// TODO Auto-generated constructor stub
}
public CustomButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
// TODO Auto-generated constructor stub
}
private void init(){
Typeface font_type=Typeface.createFromAsset(getContext().getAssets(), "font/ProximaNova-Bold.ttf");
setTypeface(font_type);
}
}
Now you can use the button in xml as given below.
<model.CustomButton
android:id="#+id/search"
android:layout_width="#dimen/edittext_width_large"
android:layout_height="#dimen/button_height"
android:layout_below="#+id/cars"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/pad_20dp"
android:background="#drawable/button_pressed_bg"
android:text="#string/find_car"
android:textColor="#color/white" />
You can use the below code. Just replace the font name in mTextFont() method as per your requirement.
public class Button_Roboto_Regular extends Button {
public Button_Roboto_Regular(Context context) {
super(context);
mTextFont(context);
}
public Button_Roboto_Regular(Context context, AttributeSet attrs) {
super(context, attrs);
mTextFont(context);
}
public Button_Roboto_Regular(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTextFont(context);
}
private void mTextFont(Context context) {
Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular_0.ttf");
this.setTypeface(face);
}
Try this. Also useful for EditTextViews, TextViews.. whatever!
<your.namespace.app.FontButton
app:font="montserrat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
How is possible? This way!
public class FontButton extends Button {
public FontEditText(Context context) {
this( context, null );
}
public FontEditText(Context context, AttributeSet attrs) {
this( context, attrs, 0 );
init( context, attrs );
}
public FontEditText(Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
init( context, attrs );
}
public FontEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super( context, attrs, defStyleAttr, defStyleRes );
init( context, attrs );
}
private void init(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes( attrs, R.styleable.Fonts );
if ( ta != null ) {
String fontAsset = ta.getString( R.styleable.Fonts_font );
if ( !StringUtils.isEmpty( fontAsset ) ) {
int type = Integer.parseInt( fontAsset );
Typeface typeFace = FontManager.getInstance( context ).getByType( type );
ta.recycle();
super.setTypeface( typeFace );
}
}
}
}
public class FontManager {
private static FontManager Instance;
private Context context;
private Typeface robotoCondensedBold;
private Typeface robotoCondensed;
private Typeface robotoLight;
private Typeface kronica;
private Typeface montserrat;
private Typeface montserratLight;
private Typeface keepCalmMedium;
private FontManager(Context context) {
this.context = context;
this.robotoCondensedBold = Typeface.createFromAsset( context.getAssets(), "fonts/RobotoCondensed-Bold.ttf" );
this.robotoCondensed = Typeface.createFromAsset( context.getAssets(), "fonts/RobotoCondensed-Regular.ttf" );
this.robotoLight = Typeface.createFromAsset( context.getAssets(), "fonts/Roboto-Light.ttf" );
this.kronica = Typeface.createFromAsset( context.getAssets(), "fonts/kronika.ttf" );
this.montserrat = Typeface.createFromAsset( context.getAssets(), "fonts/Montserrat-Regular.ttf" );
this.montserratLight = Typeface.createFromAsset( context.getAssets(), "fonts/Montserrat-Light.ttf" );
this.keepCalmMedium = Typeface.createFromAsset( context.getAssets(), "fonts/KeepCalmMedium.ttf" );
}
public synchronized static FontManager getInstance(Context context) {
if ( Instance == null )
Instance = new FontManager( context );
return Instance;
}
public Typeface getByType(int type) {
switch ( type ) {
case 0:
return FontManager.getInstance( context ).getRobotoCondensedBold();
case 1:
return FontManager.getInstance( context ).getRobotoLight();
case 2:
return FontManager.getInstance( context ).getKronica();
case 3:
return FontManager.getInstance( context ).getRobotoCondensed();
case 4:
return FontManager.getInstance( context ).getMontserrat();
case 5:
return FontManager.getInstance( context ).getMontserratLight();
case 6:
return FontManager.getInstance( context ).getKeepCalmMedium();
default:
return Typeface.DEFAULT;
}
}
public Typeface getRobotoCondensedBold() {
return robotoCondensedBold;
}
public Typeface getKronica() {
return kronica;
}
public Typeface getRobotoCondensed() {
return robotoCondensed;
}
public Typeface getRobotoLight() {
return robotoLight;
}
public Typeface getMontserrat() {
return montserrat;
}
public Typeface getMontserratLight() {
return montserratLight;
}
public Typeface getKeepCalmMedium() {
return keepCalmMedium;
}
In addition, a font_attrs.xml in your res folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Fonts">
<attr name="font" format="enum">
<enum name="robotoCondensedBold" value="0"/>
<enum name="robotoLight" value="1"/>
<enum name="kronica" value="2"/>
<enum name="robotoCondensed" value="3"/>
<enum name="montserrat" value="4"/>
<enum name="montserratLight" value="5"/>
<enum name="keepCalmMedium" value="6"/>
</attr>
</declare-styleable>
</resources>
Note that you only need to modify the FontManager and the font_attrs.xml to customize your fonts!
In kotlin you can create your custom button and override the typeface.
class StandardButton #JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, dyfStyleAttr: Int = 0) : AppCompatButton(context, attrs, dyfStyleAttr) {
init {
typeface = Typeface.createFromAsset(context.assets, "fonts/CopperplateGothicBold.ttf")
}
}

Custom Fonts and Custom Textview on Android

From an application I need to develop, I've received a specific font that has many files like FontName-Regular, FontName-Bold, FontName-it. I need to use it in all the textviews in the application. First I thought it was an easy task. Look over SO and found a very nice thread:here
So first I did like:
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(FONT_REGULAR);
}
} catch (Exception e) {
e.printStackTrace();
// ignore
}
}
And called this method during onCreate in my activity. Every textView in my app was showing that font and boy, was I happy for getting away so easy. Until I got to a screen where some textviews required Bold as Style (android:textStyle="bold"). Then I realized that this solution does not provide me with possibility to load the Font-Bold.ttf from assets.
Than looked further and saw a nice custom TextView implementation, in the same SO question:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
public void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf");
setTypeface(tf ,1);
}
}
This looks even better. My question is: how can I detect on init() if my control has Style set to Bold or not so I can assign the requested TypeFace ?
Thank you for your time.
LE. Following the example below, I've updated my class as:
public class MyTextView extends TextView {
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_BOLD);
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
Well If I debug, the app goes in setTypeFace and it seems to apply the bold one, but on my layout I can't see any change, not bold. No matter what font I use, no changes are done in my TextView and is displayed with the default android font. I wonder why ?
I have summed everything on a blog post here on my blog maybe it will help someone.
The constructor of TextView calls setTypeface(Typeface tf, int style) with the style parameter retrieved from the XML attribute android:textStyle. So, if you want to intercept this call to force your own typeface you can override this method as follow:
public void setTypeface(Typeface tf, int style) {
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/your_normal_font.ttf");
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/your_bold_font.ttf");
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
You can use my CustomTextView which allows you to specify a font file name in your assets folder:
https://github.com/mafshin/CustomTextView
and the usage is really simple:
<com.my.app.CustomTextView
xmlns:custom="http://schemas.android.com/apk/res/com.my.app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test text"
android:id="#+id/testcustomview"
custom:fontAssetName="Politica XT.otf"
/>
I think it's better to create your own package for custom fonts and import them in your project so that you can use them later in future
package com.codeslips.utilities;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomTextView extends TextView {
public CustomTextView(Context context)
{ super(context); setFont(); }
public CustomTextView(Context context,AttributeSet set)
{ super(context,set); setFont(); }
public CustomTextView(Context context,AttributeSet set,int defaultStyle)
{ super(context,set,defaultStyle); setFont(); }
private void setFont() {
Typeface typeface=Typeface.createFromAsset(getContext().getAssets(),"fonts/your-font.ttf");
setTypeface(typeface); //function used to set font
}
}
Now use the above class in your XML file to have your custom font
<com.codeslips.utilities.CustomTextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Upload Image"
android:paddingTop="10sp"
android:textSize="14sp"
android:layout_weight="0.7"
android:textColor="#android:color/white"/>

Categories

Resources