Android – Fonts

Acest tutorial are ca scop exemplificarea modului  în care poate fi aplicat un font mai multor butoane(se poate aplica și pentru alt tip de controale), în cadrul aplicației.



1.Implementarea unei clase care să extindă clasa Button

public class ButtonPlus extends Button {
 public ButtonPlus(Context 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);


2. Implementarea unei clase care acceseaza memorie puțină.


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;

 3. Implementarea unei clase helper utilă în a seta fontul.

public class CustomFontHelper {

* Sets a font on a textview based on the custom 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);

* 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) {
Typeface tf = FontCache.get(font, context);
if(tf != null) {



4. Definirea noului atribut de tip style.


<?xml version="1.0" encoding="utf-8"?>
 <declare-styleable name="CustomFont">
 <attr name="font" format="string"/>


5. Cum poate fi utilizat?



<style name="button" parent="@android:style/Widget.Button">
<item name="">fonts/copperplate_gothic_light.TTF</item>

Android – Fonts

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s