17

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

4

7 回答 7

25

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

1.您要将“Helv Neue 67 Med Cond.ttf”保存到资产文件夹中。然后

对于文本视图

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

对于按钮

  Button n=(Button) findViewById(R.id.button1);
  Typeface typeface = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
  n.setText("show");
  n.setTypeface(typeface);
于 2013-08-15T10:55:51.087 回答
17

首先,您必须将 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);
于 2011-06-16T13:37:58.110 回答
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);
        }
    }

这是用于减少旧设备上的内存使用的 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;
    }
}

最后是布局中的一个示例:

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

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

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

于 2016-02-05T11:51:04.387 回答
2
于 2011-06-16T13:47:43.273 回答
1

您可以使用:

android:typeface="yourfont"
于 2011-06-16T13:17:13.283 回答
0

您必须下载Helv Neue 67 Med Cond字体并将其存储在资产文件夹中。让下载的字体是myfont.ttf

使用以下代码设置字体

Typeface tf = Typeface.createFromAsset(getAssets(), "myfont.ttf");
        TextView TextViewWelcome = (TextView)findViewById(R.id.textViewWelcome);
        TextViewWelcome.setTypeface(tf);

谢谢迪帕克

于 2011-06-16T13:47:42.060 回答
0

这是一篇很好的文章,我用过几次并且有效:http: //mobile.tutsplus.com/tutorials/android/customize-android-fonts/

于 2011-06-16T14:18:10.067 回答