Java 设置导航视图标题的自定义字体
我创建了一个android studio默认导航视图,并在nav_header_main.xml中放置了两个按钮(见下图) 现在我想为按钮设置自定义字体。 我在MainActivity.java中尝试了以下方法:Java 设置导航视图标题的自定义字体,java,android,android-layout,android-studio,Java,Android,Android Layout,Android Studio,我创建了一个android studio默认导航视图,并在nav_header_main.xml中放置了两个按钮(见下图) 现在我想为按钮设置自定义字体。 我在MainActivity.java中尝试了以下方法: Typeface font = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf"); Button b = (Button) findViewById(R.id.login_btn); b.setType
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
Button b = (Button) findViewById(R.id.login_btn);
b.setTypeface(font);
但是它不起作用!!
我该怎么做
您必须编写一个从按钮扩展的自定义类 这里有一个例子:
package com.example.test;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.TextView;
public class CustomFontButton extends Button {
public CustomFontButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomFontButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomFontButton(Context context) {
super(context);
init();
}
private void init() {
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
setTypeface(font);
}
}
<com.example.test.CustomFontButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Text" />
从XML使用它:
package com.example.test;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.TextView;
public class CustomFontButton extends Button {
public CustomFontButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomFontButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomFontButton(Context context) {
super(context);
init();
}
private void init() {
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
setTypeface(font);
}
}
<com.example.test.CustomFontButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button Text" />
创建自定义类扩展Button类,然后使用该类使用xml而不是默认值创建按钮!看看这个答案,请准确解释“它不起作用”的原因。