You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Fragment横竖屏切换后字体设置方法失效求助

解决Fragment横竖屏切换后字体设置失效的问题

我来帮你搞定这个横竖屏切换后字体不生效的问题~ 核心原因其实很简单:横竖屏切换时Fragment会经历销毁重建的生命周期,你原来设置字体的代码只在第一次创建View时执行了一次,重建后没有重新触发,所以字体就变回默认的了。下面给你几个实用的解决方案:

方案一:在Fragment生命周期方法中重新调用字体设置

在Fragment的onViewCreated或者onResume方法里重新执行overrideFonts,因为这两个方法在每次Fragment重建后都会被调用:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // 传入Fragment的根View,重新遍历设置字体
    overrideFonts(requireContext(), view);
}

这个方法最直接,改动最小,适合快速解决问题。

方案二:优化字体加载逻辑,避免重复创建Typeface

你原来的代码每次调用overrideFonts都会重新从Asset加载字体,不仅浪费资源,还可能引发意外问题。我们可以把Typeface缓存起来,复用同一个实例:

// 定义一个缓存的Typeface变量,放在Fragment或者Application中
private Typeface mCustomFont;

// 初始化字体,只加载一次
private void initCustomFont(Context context) {
    if (mCustomFont == null) {
        try {
            mCustomFont = Typeface.createFromAsset(context.getAssets(), "font/aFont.ttf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// 修改后的overrideFonts方法
public void overrideFonts(final Context context, final View v ) {
    initCustomFont(context);
    if (mCustomFont == null) return; // 加载失败直接返回
    
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
            }
        } else if (v instanceof TextView) {
            ((TextView) v).setTypeface(mCustomFont);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

搭配方案一使用,既解决了横竖屏的问题,又提升了性能。

方案三:自定义TextView,一劳永逸

如果你的项目中有大量TextView需要设置字体,推荐用自定义TextView的方式,从根源上解决问题:

public class CustomFontTextView extends AppCompatTextView {

    public CustomFontTextView(Context context) {
        super(context);
        setupFont(context);
    }

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setupFont(context);
    }

    public CustomFontTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setupFont(context);
    }

    private void setupFont(Context context) {
        try {
            Typeface font = Typeface.createFromAsset(context.getAssets(), "font/aFont.ttf");
            setTypeface(font);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

之后在布局文件里用CustomFontTextView代替原生的TextView:

<com.yourpackage.CustomFontTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World"/>

这样不管Fragment怎么重建,TextView都会自动加载自定义字体,再也不用手动调用overrideFonts了。


内容的提问来源于stack exchange,提问作者cup code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:54:38