3

我想在设计支持库中的 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);
}

欢迎提出任何建议。

4

2 回答 2

6

如果你getPageTitle在你的FragmentPagerAdapter, 然后调用

mTabs.setupWithViewPager(mFragmentPager);

选项卡文本已为您设置。

然后为了改变我使用这个方法的字体从这个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);
    }
}
于 2015-08-12T10:55:10.190 回答
0

你只需在下面添加代码

int wantedTabIndex = 0;

TextView tv = (TextView)(((LinearLayout)

((LinearLayout)tabLayout_main.getChildAt(0)).getChildAt(wantedTabIndex)).getChildat(1));
 tv.setText("your title");

tv.setTypeFace(customfont);

上面代码中的 WanttabIndex 是你的标签位置

于 2016-10-04T05:59:59.983 回答