我目前正在尝试使用"com.google.android.material.tabs.TabLayout"更改活动选项卡的字体。我查找了几个解决方案,如Typeface.createFromAssets(),但它会导致崩溃。我不使用 Typeface.BOLD 的原因是因为它是一个单独的字体文件还是我错过了什么?
有没有另一种解决方案可以在运行时更改选项卡的字体?
创建
自己的TextView
类模型:
public class MyTextViewModel extends TextView {
String font_path = "fonts/Your_font.ttf";
public MyTextViewModel(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Typeface tf = Typeface.createFromAsset(context.getAssets(), font_path);
this.setTypeface(tf);
}
public MyTextViewModel(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface tf = Typeface.createFromAsset(context.getAssets(), font_path);
this.setTypeface(tf);
}
public MyTextViewModel(Context context) {
super(context);
Typeface tf = Typeface.createFromAsset(context.getAssets(), font_path);
this.setTypeface(tf);
}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
}
}
然后创建一个 xml 文件,调用它tab_text,使用您的 MyTextViewModel
<?xml version="1.0" encoding="utf-8"?>
<MyTextViewModel
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@android:id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
/>
,然后将其应用于您选择的选项卡 ID
MyTextViewModel tv = LayoutInflater.from(this).inflate(R.layout.tab_text,null)
tabLayout.getTabAt(i).setCustomView(tv);