在android中设置Button文本字体

Ajn*_*Ajn 14 android android-layout android-fonts android-button

我有一个button使用Android小部件创建.我想将按钮文本的字体设置为Helv Neue 67 Med Cond.如何获取此字体并将其设置为android布局文件中的按钮文本?

Ann*_*Ann 24

我想你可能已经找到了答案,但如果没有(对于其他开发人员),你可以这样做:

1.您想将"Helv Neue 67 Med Cond.ttf"保存到assets文件夹中.然后

对于TextView

  TextView txt = (TextView) findViewById(R.id.custom_font);
  Typeface typeface = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
  txt.setTypeface(typeface);
Run Code Online (Sandbox Code Playgroud)

对于Button

  Button n=(Button) findViewById(R.id.button1);
  Typeface typeface = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
  n.setText("show");
  n.setTypeface(typeface);
Run Code Online (Sandbox Code Playgroud)


Par*_*ani 16

首先,你必须将ttf文件放在assets文件夹中然后你可以使用下面的代码在TextView中设置自定义字体,就像你可以为Button做的一样:

TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
txt.setTypeface(font);
Run Code Online (Sandbox Code Playgroud)


Cab*_*zas 5

如果您打算为多个按钮添加相同的字体,我建议您一路实现子类按钮:

public class ButtonPlus extends Button {

    public ButtonPlus(Context context) {
        super(context);
        applyCustomFont(context);
    }

    public ButtonPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyCustomFont(context);
    }

    public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        applyCustomFont(context);
    }

    private void applyCustomFont(Context context) {
            Typeface customFont = FontCache.getTypeface("fonts/candy.ttf", context);
            setTypeface(customFont);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是用于减少旧设备上内存使用的 FontCache:

public class FontCache {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<>();

    public static Typeface getTypeface(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后在布局中使用示例:

 <com.my.package.buttons.ButtonPlus
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_sometext"/>
Run Code Online (Sandbox Code Playgroud)

这似乎是一项艰巨的工作,但是一旦您有几个要更改字体的按钮和文本字段,您就会感谢我。

您也可以在GitHub 中查看本教程和示例。