最近开发的一款产品,不同的内容、模块使用了很多种字体。我在application里面设置了一种全局的字体,在普通的textView都已生效,但是在tabLayout里面却未生效,以下方法可以修改tabLayout 里面的字体:
//更改字体
public void changeTabsFont(XTabLayout tabLayout) {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(TypefaceCache.getInstance(mContext).get("HarmonyOS_Sans_SC_Regular.ttf"));
}
}
}
}
以下是我自己的TypefaceCache类,可直接使用:
public class TypefaceCache {
private static TypefaceCache sInstance;
private final Hashtable<String, Typeface> mCache = new Hashtable<String, Typeface>();
private final Application mApplication;
private TypefaceCache(Application application) {
mApplication = application;
}
/**
* If the cache has an instance for the typeface name, this will return the instance immediately.
* Otherwise this method will create typeface instance and put it into the cache and return the instance.
*
* @param name the typeface name.
* @return {@link Typeface} instance.
*/
public synchronized Typeface get(String name) {
Typeface typeface = mCache.get(name);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(mApplication.getAssets(), name);
} catch (Exception exp) {
return null;
}
mCache.put(name, typeface);
}
return typeface;
}
/**
* Retrieve this cache.
*
* @param context the context.
* @return the cache instance.
*/
public static synchronized TypefaceCache getInstance(Context context) {
if (sInstance == null) {
sInstance = new TypefaceCache((Application) context.getApplicationContext());
}
return sInstance;
}
}
PS:使用此方法,在初始化的时候的确可以达到修改字体的目的,但是在切换viewPager的时候又恢复到了默认的字体,所以我又在在viewPager的addOnPageChangeListener()里面又调用了一次,每次切换的时候重新设置,就解决了此问题










