Typeface in xml from another class - android

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");
}
}

Related

Stroke in textview text android?

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"
/>

Setting Custom Font for TextView causing the onCreate to take longer to build

I am currently implementing Roboto font within my project. For some fragments, there are a lot of TextView's. I am creating a custom View that exends TextView to implement custom fonts. Is there a better way to load the fonts without increasing the onCreate times?
Extends TextView
public class TextViewFont extends TextView {
public TextViewFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public TextViewFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TextViewFont(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextViewFont);
String fontName = a.getString(R.styleable.TextViewFont_fontName);
if (fontName != null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
XML
<com.eugene.fithealthmaingit.Custom.TextViewFont
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:text="#string/dinner"
android:textColor="#color/text_color"
android:textSize="16sp"
app:fontName="Roboto-Regular.ttf"/>
Example of how many TextView's
This is the library that saved my life Calligraphy. It's really nice and easy to use.
Typeface.createfromassets is a time taking process. You should declare typeface as static varaiable in class and just use it in constructor.
But here you are loading fonts in every textview's constructor.
If you having multiple fonts, have all tytypeface as static and use it appropriately.
UPDATE CODE:
public class TextViewFont extends TextView {
public static Typeface typeface1 = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontName1");
public static Typeface typeface2 = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontName2");
public static Typeface typeface3 = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontName3");
public static Typeface typeface4 = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontName4");
public static Typeface typeface5 = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontName5");
public TextViewFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public TextViewFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TextViewFont(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextViewFont);
String fontName = a.getString(R.styleable.TextViewFont_fontName);
if (fontName != null) {
setTypeface(getTypeFace(fontName));
}
a.recycle();
}
}
public Typeface getTypeFace(String fontName){
if(fontName.equals("fontName1")){
return typeface1;
}else if(fontName.equals("fontName2")){
return typeface2;
}else if(fontName.equals("fontName3")){
return typeface3;
}else if(fontName.equals("fontName4")){
return typeface4;
}else if(fontName.equals("fontName5")){
return typeface5;
}
}
}
}
Try using an instance singleton or applicationsingleton. See if this works. So you can just call TextLover.get(context).getFont(id). It will create and cache it on the fly. This way your other views can also reuse the font cache. eg. buttons
class TextLover {
private static TextLover singleton;
private final Context context;
private final SparseArray<Typeface> faces = new SparseArray<Typeface>();
public TextLover get(Context context) {
if (singleton == null) {
singleton = new TextLover(context);
}
return singleton;
}
private TextLover(Context context) {
this.context = context;
}
private static final String[] fonts = {
"fonts/fontName1",
"fonts/fontName2",
"fonts/fontName3",
"fonts/fontName4",
"fonts/fontName5",
...
"fonts/fontName100"
}
// NOTE you need a mapping of ids to each asset font in fonts[]
public Typeface getFont(int id) {
Typeface font = faces.get(id);
if (font == null) {
font = Typeface.createFromAsset(context.getAssets(), fonts[id]);
faces.append(id, font);
}
return font;
}
}

Android set font for custom TextView widget

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);
}
}

How to set custom fonts on EditText in Android?

I am trying to implement a custom typeface on an EditText. Does anyone have a better approach as opposed to what I'm currently doing?
Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
edittext.setTypeface(myFont);
Because I have lots of EditTexts...
public class CEditText extends EditText {
private Context context;
private AttributeSet attrs;
private int defStyle;
public CEditText(Context context) {
super(context);
this.context=context;
init();
}
public CEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
this.attrs=attrs;
init();
}
public CEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context=context;
this.attrs=attrs;
this.defStyle=defStyle;
init();
}
private void init() {
Typeface font=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
this.setTypeface(font);
}
#Override
public void setTypeface(Typeface tf, int style) {
tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
super.setTypeface(tf, style);
}
#Override
public void setTypeface(Typeface tf) {
tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
super.setTypeface(tf);
}
call this class in XML as follows
<yourpackagename.CEditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
</yourpackagename.CEditText>
Create a new class that extends EditText like
public class CustomEditTextNormal extends EditText
{
public CustomEditTextNormal(Context context)
{
super(context);
init(context);
}
public CustomEditTextNormal(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context);
}
public CustomEditTextNormal(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init(context);
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
}
public void init(Context context)
{
try
{
Typeface myFont = Typeface.createFromAsset(context.getAssets(), "fonts/myfont.ttf");
setTypeface(mSearchAndSend.HelveticaLight);
}
catch (Exception e)
{
Logger.LogError(e);
}
}
}
and include it on your XML like
<com.package.name.CustomEditText/>
How about create a new class that inherits EditText and sets the typeface you want and then instantiate the new class in the xml?
Create a new class which inherits from EditText, and then override the public void setTypeface(Typeface tf, int style) method and add your own font.
You need to make one method in Common class Like,
public void setExternalFonts(EdiText tv) {
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"fonts/myfont.ttf");
tv.setTypeface(tf);
}
Now call this method as
yourClassName.setExternalFonts(yourEditText);
Create a new class which inherits from EditText, and then override the public void setTypeface(Typeface tf, int style) method and add your own font.
And use in your activity like this
FontLoader.setQuickSandTypeface(YourEditText) in your activity
try this one
public 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 EditText) {
((EditText) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "roboto_thin.ttf"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try this. Also useful for Buttons, TextViews.. whatever!
<your.namespace.app.FontEditText
app:font="montserrat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
How is possible? This way!
public class FontEditText extends EditText {
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!

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")
}
}

Categories

Resources