How to embed font into tab layout from android design support

I want to add custom font to tablayout from design support library. I am trying to set a custom view that already sets the font. But it doesn't work. Just enter the system font.

What I've done,

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);
}

      

Welcome any suggestion.

+3


source to share


2 answers


If you override getPageTitle

in FragmentPagerAdapter

then call

mTabs.setupWithViewPager(mFragmentPager);

      

the tab text is set for you.

Then, to change the font, I used this method from 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);
            }
        }
    }

      

Here FragmentPagerAdapter

's a whole for your reference

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);
    }
}

      

+6


source


you just add below code

int wantedTabIndex = 0;

TextView tv = (TextView)(((LinearLayout)

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

tv.setTypeFace(customfont);

      



the WantTabIndex in the above code is your tab

0


source







All Articles