簡體   English   中英

Android:如何將自定義字體應用於 TabLayout 中的活動選項卡?

[英]Android: How can I apply a custom font to an active tab in TabLayout?

我目前正在嘗試使用“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);
}
}

然后使用您的 MyTextViewModel 創建一個名為 tab_text 的 xml 文件

<?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"
/>

然后將其應用於您選擇的 TabID

 MyTextViewModel tv = LayoutInflater.from(this).inflate(R.layout.tab_text,null)
 tabLayout.getTabAt(i).setCustomView(tv);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM