i'm wrote simple widget as textview with some attributes and i want to set font for that in extended TextView class, how to do this action and i can be have this ability?
atributes:
<resources>
<declare-styleable name="TextViewStyle">
<attr name="selected_background" format="integer" />
<attr name="font" format="string" />
</declare-styleable>
</resources>
custom textview widget:
public class TextViewStyle extends TextView{
public TextViewStyle(Context context) {
super(context);
}
public TextViewStyle(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TextViewStyle(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewStyle, defStyle, 0);
a.recycle();
}
}
simple UI widget into xml:
<ir.jaziire.widgets.TextViewStyle
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/topic"
android:textColor="#000"
android:textSize="14dp"
android:gravity="right"
/>
in this widget i want to set app:font="" to set any font from asset
CustomTextView:
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;
import com.androidhub.R;
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
try {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.font, defStyle, 0);
String str = a.getString(R.styleable.font_fonttype);
a.recycle();
switch (Integer.parseInt(str)) {
case 0:
str = "fonts/Trebuchet_MS.ttf";
break;
default:
break;
}
setTypeface(FontManager.getInstance(getContext()).loadFont(str));
} catch (Exception e) {
e.printStackTrace();
}
}
public CustomTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
#SuppressWarnings("unused")
private void internalInit(Context context, AttributeSet attrs) {
}
FontManager:
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.graphics.Typeface;
public class FontManager {
private Map<String, Typeface> fontCache = new HashMap<String, Typeface>();
private static FontManager instance = null;
private Context mContext;
private FontManager(Context mContext2) {
mContext = mContext2;
}
public synchronized static FontManager getInstance(Context mContext) {
if (instance == null) {
instance = new FontManager(mContext);
}
return instance;
}
public Typeface loadFont(String font) {
if (false == fontCache.containsKey(font)) {
fontCache.put(font,
Typeface.createFromAsset(mContext.getAssets(), font));
}
return fontCache.get(font);
}
}
in attrs.xml file:
<declare-styleable name="font">
<attr name="fonttype">
<enum name="trebuchet_ms" value="0" />
</attr>
</declare-styleable>
Use your CustomTextView in your xml as:
declare this in top of your xml
xmlns:custom="http://schemas.android.com/apk/res/com.androidhub"
And you can use your CustomTextView as :
<com.utils.CustomTextView
android:id="#+id/loadMap"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#drawable/custom_button_selector"
android:clickable="true"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:gravity="center"
android:marqueeRepeatLimit="marquee_forever"
android:padding="10dp"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/load_map"
android:textColor="#color/home_buttons_selector"
android:textSize="16sp"
custom:fonttype="trebuchet_ms" />
Make sure your are placing your font in assests-->fonts-->YourFont
com.androidhub is my package name.
I used this in my project it may help You.
TextViewEx.java
public class TextViewEx extends TextView {
public enum TextStyle {BOLD,LIGHT,REGULAR,SEMIBOLD,EXOREGULAR,BOLDLARGE};
TypedArray Canvasattrs=null;
int CurvatureDegree;
boolean isCurvature = false;
String direction;
String RVal;
public TextViewEx(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public TextViewEx(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs){
if (!this.isInEditMode()) { // used for preview while designing.
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView_TypeFace)
Typeface font = null;
String Type = a.getString(R.styleable.TextView_TypeFace_TypeFace);
if(Type == null){
UserTypeFace.SetRegular(this); //Set Default Font if font is not defined in xml
return;
}
setStyle(Type);
} else {
setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
}
}
private void setStyle(String style){
TextStyle value = TextStyle.valueOf(style); //convert String to ENUM
switch (value){
case BOLD:UserTypeFace.SetBold(this);
break;
case LIGHT:UserTypeFace.Setlight(this);
break;
case REGULAR:UserTypeFace.Setthin(this);
break;
case SEMIBOLD:UserTypeFace.SetSEMIBOLD(this);
break;
case EXOREGULAR:UserTypeFace.SetRegular(this);
break;
case BOLDLARGE:UserTypeFace.SetBoldLarge(this);
break;
}
}
}
UserTypeFace.java
public class UserTypeFace {
public static final String BOLD;
public static final String LIGHT;
public static final String REGULAR;
public static final String EXOREGULAR;
public static final String BOLDLARGE;
public static final String SEMIBOLD;
static {
REGULAR="fonts/JosefinSans-Bold.ttf";
LIGHT="fonts/JosefinSans-Bold.ttf";
BOLD="fonts/JosefinSans-Bold.ttf";
SEMIBOLD="fonts/JosefinSans-Bold.ttf";
BOLDLARGE="fonts/JosefinSans-Bold.ttf";
EXOREGULAR="fonts/Exo2-Regular.ttf";
}
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
private static Typeface getTypeFace(Context context, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface typeFace = Typeface.createFromAsset(
context.getAssets(), assetPath);
cache.put(assetPath, typeFace);
} catch (Exception e) {
Log.e("TypeFaces", "Typeface not loaded.");
return null;
}
}
return cache.get(assetPath);
}
}
public static void Setthin(TextView obj){
obj.setTypeface(getTypeFace(obj.getContext(),EXOREGULAR), Typeface.NORMAL);
}
public static void Setlight(TextView obj){
obj.setTypeface(getTypeFace(obj.getContext(),LIGHT), Typeface.NORMAL);
}
public static void SetBold(TextView obj){
obj.setTypeface(getTypeFace(obj.getContext(),BOLD), Typeface.NORMAL);
}
public static void SetSEMIBOLD(TextView obj){
obj.setTypeface(getTypeFace(obj.getContext(),SEMIBOLD), Typeface.NORMAL);
}
public static void SetRegular(TextView obj){
obj.setTypeface(getTypeFace(obj.getContext(),EXOREGULAR), Typeface.NORMAL);
}
public static void SetBoldLarge(TextView obj){
obj.setTypeface(getTypeFace(obj.getContext(),BOLDLARGE), Typeface.BOLD);
}
public static Typeface getRegular(View obj){
return getTypeFace(obj.getContext(),EXOREGULAR);
}
}
Add this in attrs.xml
<resources>
<declare-styleable name="TextView_TypeFace">
<attr name="TypeFace" format="reference|string" localization="suggested" />
</declare-styleable>
</resources>
And You Will be adding this in layout file like
<pakage.name.TextViewEx
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:textColor="#282828"
attrs:TypeFace="#string/Bold"
android:textSize="30sp"
android:text=" Please Login "
android:id="#+id/txtlogin" />
Use the following code:
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
createFont();
}
public MyTextView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
createFont();
}
public MyTextView(Context context, AttributeSet attr) {
super(context, attr);
createFont();
}
private void createFont() {
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "SHRUTI.TTF");
setTypeface(font);
}
}
Related
I am using a text view for font awesome icon.and setting typeface programmatically`.
findviewbyid(R.id.mytextview).setTypeface(FontManager.getTypeface(getApplicationContext(), FontManager.FONTAWESOME));
is it possible to set typeface from another class
? i know there is one attribute .
android:typeface
i want to set that above typeface in xml.please dont ask me why i need it.thank you..FontManager class is given below
public class FontManager {
public static final String ROOT = "fonts/",
FONTAWESOME = ROOT + "fontawesome-webfont.ttf";
public static Typeface getTypeface(Context context, String font) {
return Typeface.createFromAsset(context.getAssets(), font);
}}
You need to create a class that extends TextView and override a few methods to accomplish what you need:
TypeFaceTextView:
public class TypefaceTextView extends android.support.v7.widget.AppCompatTextView {
public TypefaceTextView(Context context) {
super(context);
}
public TypefaceTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TypefaceTextView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(
attrs,
R.styleable.TypefaceTextView);
try {
CharSequence typeText = a.getString(R.styleable.TypefaceTextView_typeText);
TypeText type = TypeText.valueOf(String.valueOf(typeText));
switch (type){
case title:
setTypeface(Typefaces.getTitleLatoTypeface(getContext()));
break;
case body:
setTypeface(Typefaces.getBodyLatoTypeface(getContext()));
break;
case footer:
setTypeface(Typefaces.getFooterLatoTypeface(getContext()));
break;
default:
break;
}
} finally {
a.recycle();
}
}
private enum TypeText{
title,
body,
footer
}
}
Create a file called attrs.xml in values folder and declare the stylable used in TypeFaceTextView:
<resources>
<declare-styleable name="TypefaceTextView">
<attr name="typeText" format="string" />
</declare-styleable>
Then in your xml you can use it like this:
<com.playtown.set_br.utils.TypefaceTextView
android:id="#+id/text_view"
...
app:typeText="title" />
Here is my TypeFaces class just in case you need it:
public class Typefaces {
public static Typeface getTitleLatoTypeface(Context context){
return Typeface.createFromAsset(context.getAssets(),"Lato-Bold.ttf");
}
public static Typeface getFooterLatoTypeface(Context context){
return Typeface.createFromAsset(context.getAssets(),"Lato-Hairline.ttf");
}
public static Typeface getBodyLatoTypeface(Context context){
return Typeface.createFromAsset(context.getAssets(),"Lato-Regular.ttf");
}
}
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>
I need to style the text for textview as per the below image
The font being used is CARTER ONE font
This is my textview class
public class CustomTextViewCarter extends TextView {
private static Typeface mTypeface;
public CustomTextViewCarter(final Context context) {
this(context, null);
}
public CustomTextViewCarter(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextViewCarter(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (!isInEditMode()) {
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getResources().getAssets(), "carter_one.ttf");
}
setTypeface(mTypeface);
}
}
}
But the the same kind of text doesn't appear. How can it be done?
Use this code for show custom TextView
Step-1:
CustomTextView.java
public class CustomTextView extends TextView {
private static final String TAG = "TextView";
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomTextView(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.CustomTV);
String customFont = a.getString(R.styleable.CustomTV_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;
}
}
Step-2:
After that write below code in your styles.xml file
<declare-styleable name="CustomTV">
<attr name="customFont" format="string"></attr>
</declare-styleable>
Step-3:
Use CustomTextView in your xml file
Here com.app.demo is my package name.. use your package name instead of that,
<com.app.demo.CustomTextView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello"
android:textColor="#color/text"
android:textStyle="bold"
app:customFont="carter_one.ttf" />
Try this.
You can set ttf by making your own textview implementation.
It will works above API 15 (Ice cream sandwich).
https://stackoverflow.com/a/5185587/850347
<com.lht.ui.MyTextView
android:text="Hello friends"
lht:ttf_name="ITCBLKAD.TTF"
/>
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);
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")
}
}