如果您以前没有尝试过使用字体。我建议删除您的资产文件夹,在您的 res 文件夹中创建一个新的资产文件夹,然后将其移回原来的位置。有时 Android Studio 不接受构建的资产文件夹。
如这里所示Runtime Exception: Font not found for every font i've tried - Android
另外,我建议创建一个扩展 Button 的类,以便在您为按钮分配正确的 XML 时自动为该小部件设置字体。
一个例子是:
public class CustomFontButton extends Button {
AttributeSet attr;
public CustomFontButton(Context context) {
super(context);
setCustomFont(context, attr);
}
public CustomFontButton(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomFontButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
String customFont = null;
TypedArray a = null;
if (attrs != null) {
a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomFontButton);
customFont = a.getString(R.styleable.CustomFontButton_customFont);
}
if (customFont == null) customFont = "fonts/OldEnglishFive.ttf";
setCustomFont(ctx, customFont);
if (a != null) {
a.recycle();
}
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e("textView", "Could not get typeface", e);
return false;
}
setTypeface(tf);
return true;
}
}
然后在你的xml中你只需要改变
<yourpackagename.CustomFontButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="220dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="doSomething"
android:text="TEXT" />
在你的 values 文件夹中创建一个 attrs.xml。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontButton">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources >
这将使您不必在每次想要在按钮上使用自定义字体(或大多数其他小部件,可以应用相同的逻辑)时都执行setTypeFace