如果您尚未使用的字體試過前面。我會建議刪除您的資產文件夾,在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" />
創建自己的價值觀的文件夾內的attrs.xml。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontButton">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources >
這將節省你不必做setTypeFace
每次你想上的按鈕自定義字體的使用setTypeface方法直接設置字樣(或大多數其他窗口小部件,相同的邏輯可以應用)
好的,資產** _文件夾_ **沒有問題。 我認爲你提出的第二種方法很棒,但我不明白如何定義_CustomFontButton_和_CustomFontButton_customFont_。 –
在您的res文件夾中,右鍵單擊您的值文件夾並添加一個新的xml,將其稱爲attrs.xml並複製我在答案末尾添加的代碼 –
不,我實現了它,但沒有結果。 –