Справка Android по изменению типа шрифта кнопки, как? - PullRequest
19 голосов
/ 31 марта 2011

Я хотел бы изменить шрифт, отображаемый в тексте кнопки, мне удалось сделать это с помощью текста на экране, просмотра текста, но я не могу найти какую-либо информацию или помочь с применением этого к кнопке.

Я новичок, так что предоставление кода для этого было бы очень полезно.Это то, что я использую для просмотра текста, но как мне изменить шрифт кнопки?

TextView txt = (TextView) findViewById(R.id.custom_font);  
Typeface font = Typeface.createFromAsset(getAssets(), "1543Humane_jenson_bold.TTF");  
txt.setTypeface(font);

Спасибо, Люси, х

Ответы [ 5 ]

50 голосов
/ 31 марта 2011

Кнопка IS-A TextView, так что просто сделайте это, как с TextView:

Button txt = (Button) findViewById(R.id.custom_font);  
Typeface font = Typeface.createFromAsset(getAssets(), "1543Humane_jenson_bold.TTF");  
txt.setTypeface(font);
6 голосов
/ 31 марта 2011

Я использую вот так для кнопки, и она работает (так же, как для TextView) ..

 Button enter=(Button) findViewById(R.id.enter);
 Typeface type=Typeface.createFromAsset(getAssets(), "arial.ttf");
 enter.setTypeface(type);

надеюсь, это поможет ...

5 голосов
/ 01 января 2016

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

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 мы определяем настраиваемый настраиваемый атрибут

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

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

1 голос
/ 05 ноября 2018

Другая альтернатива для вышеуказанных решений:

mYourButton = (Button) findViewById(R.id.Button_id);
mYourEditText = (EditText) findViewById(R.id.editText_id);

Typeface font = ResourcesCompat.getFont(getContext(), R.font.font_name.TTF);
mYourButton.setTypeface(font);
mYourEditText.setTypeface(font);
0 голосов
/ 28 января 2019

Создавая пользовательскую кнопку, как показано здесь:

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