Как установить конкретный шрифт для текста кнопки в android?

Я хочу, чтобы текст моей кнопки находился в шрифте Copperplate Gothic Light, и я до сих пор не нашел простой чистый код для простой функции. Помогите!

PS: Поскольку для Android требуется ариэль и несколько других шрифтов, нам нужно импортировать (извинения за отсутствие лучшего слова, поскольку я новичок в этом) шрифт, который мы желаем использовать. Это все, что я смог собрать до сих пор, и здесь заканчивается тропа.

Ответ 1

Если вы планируете добавить один и тот же шрифт к нескольким кнопкам, я предлагаю вам пройти весь путь и реализовать его как стиль и подкласс:

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

Это вспомогательный класс для установки шрифта в TextView (помните, Button является подклассом TextView) на основе атрибута com.my.package: font:

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

}

И здесь FontCache для уменьшает использование памяти на более старых устройствах:

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

В res/values ​​/attrs.xml мы определяем атрибут customableable

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

И, наконец, пример использования в макете:

    <com.my.package.buttons.ButtonPlus
        style="@style/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_sometext"/>

И в 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>

Это может показаться ужасной работой, но вы поблагодарите меня, если у вас есть несколько кнопок кнопок и текстовых полей, на которые вы хотите изменить шрифт.

Ответ 2

1) Получите шрифт, который вам нужен, например, файл .ttf(CopperplateGothicLight.ttf) и поместите его в свой проект/каталог/каталог

2) Используйте этот код для обозначения шрифта и установите его на кнопку:

Typeface copperplateGothicLight = Typeface.createFromAsset(getAppContext().getAssets(), "CopperplateGothicLight.ttf"); 
yourButton.setTypeface(copperplateGothicLight);

Ответ 3

После нескольких исследований мой лучший вариант:

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

}

то Использование fontCache из первого ответа на этот вопрос: Утечка памяти с настраиваемым шрифтом для установки настраиваемого шрифта

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

Меньше кода и больше использования стандартов Android!

Ответ 4

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

Загрузите ссылку для нужного шрифта: copperplate_gothic_light

поместите его в свою папку с ресурсами.

Скриншот: enter image description here

Надеюсь, это будет полезно!

Ответ 5

Сначала загрузите файл TTF для стиля шрифта, а затем поместите его в папку assets вашего проекта.

Вы можете установить его программно следующим образом:

Typeface font_style = Typeface.createFromAsset(getAssets(), "yourcystomfontstyle.ttf");  
yourbutton.setTypeface(font_style);

Ответ 6

Вы можете использовать пользовательский класс кнопок, как указано ниже. Введите свой шрифт в папку "Ресурс/шрифт".

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

Теперь вы можете использовать кнопку в xml, как показано ниже.

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

Ответ 7

Попробуйте это. Также полезно для EditTextViews, TextViews.. что угодно!

<your.namespace.app.FontButton
     app:font="montserrat"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

Кто возможен? Таким образом!

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

Кроме того, font_attrs.xml в папке res:

<?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> 

Обратите внимание, что вам нужно только изменить FontManager и font_attrs.xml, чтобы настроить шрифты!

Ответ 8

Вы можете использовать приведенный ниже код. Просто замените имя шрифта в методе mTextFont() согласно вашему требованию.

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