我想在设计支持库的tablayout中嵌入自定义字体。我尝试设置已设置字体的自定义视图。但它没有用。只是出现系统字体。
我做的是,
mAdpater = new CustomPagerAdapter(getSupportFragmentManager());
mFragmentPager.setAdapter(mAdpater);
mTabs.setupWithViewPager(mFragmentPager);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
for (int i = 0; i < mTabs.getTabCount(); i++) {
TextView tv = new TextView(this);
tv.setText(mAdpater.getPageTitle(i));
tv.setTypeface(tf);
mTabs.getTabAt(i).setCustomView(tv);
}
欢迎任何建议。
答案 0 :(得分:6)
如果您覆盖getPageTitle
中的FragmentPagerAdapter
,请致电
mTabs.setupWithViewPager(mFragmentPager);
为您设置标签文本。
然后从this SO post
更改我使用此方法的字体 Typeface tf = Typeface.createFromAsset(getAssets(), "myfont.ttf");
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(tf);
}
}
}
以下是FragmentPagerAdapter
的完整内容供参考
class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
答案 1 :(得分:0)
您只需添加以下代码
int wantedTabIndex = 0;
TextView tv = (TextView)(((LinearLayout)
((LinearLayout)tabLayout_main.getChildAt(0)).getChildAt(wantedTabIndex)).getChildat(1));
tv.setText("your title");
tv.setTypeFace(customfont);
上面代码中的wantedtabIndex是您的标签位置