【问题标题】:Android: How can I apply a custom font to an active tab in TabLayout?Android:如何将自定义字体应用于 TabLayout 中的活动选项卡?
【发布时间】:2019-06-20 05:42:49
【问题描述】:

我目前正在尝试使用“com.google.android.material.tabs.TabLayout”更改活动标签的字体。我查找了几种解决方案,例如 Typeface.createFromAssets() ,但它会导致崩溃。 我不使用 Typeface.BOLD 的原因是因为它是一个单独的字体文件还是我遗漏了什么?

还有其他解决方案可以在运行时更改选项卡的字体吗?

【问题讨论】:

    标签: java android fonts tabs material-components-android


    【解决方案1】:

    创建自己的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);
    

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2018-02-11
      • 1970-01-01
      相关资源
      最近更新 更多