1

Hello Everyone i'm working on a tabbed app in which i have a toolbar reserved for the app logo and the tablayout with the tabs name in it,i wanted to change the font in those tabs names but i couldn't figure it out since the name are not actual textviews,i searched well in the forum and everywhere else but couldn't find anyone to answer that,so briefly what i want is to change the font in those tabs names here is my code thank you for helping!

public class MainActivity extends AppCompatActivity  {

public Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    viewPager.setCurrentItem(4);


}


private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    //here i set the fragments to use i have separate fragment.java
    // for each page i show that refers to another xml that shows the content
    //the words between "" are the tabs name and i need to change their fonts :(
    adapter.addFragment(new FiveFragment(),"ثقافة");
    adapter.addFragment(new FourFragment(), "فن");
    adapter.addFragment(new ThreeFragment(), "تعليم");
    adapter.addFragment(new TwoFragment(), "تاريخ");
    adapter.addFragment(new OneFragment(), "علوم");

    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

}

Here Is the main activity xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="0dp"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
            android:id="@+id/logo"
            android:src="@drawable/icon"
            android:layout_width="60dp"
            android:layout_height="58dp"
            android:layout_marginRight="323dp"
            android:layout_marginEnd="330dp"
            android:adjustViewBounds="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
        </LinearLayout>
    </android.support.v7.widget.Toolbar>


    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabTextColor="#000"
        app:tabTextAppearance="@style/MineCustomTabText"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#0ff"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

Anas Haxer
  • 35
  • 2
  • 8

1 Answers1

3

You can set a custom style to your TabLayout to change the font.

Using Styles

Create a new style in your styles.xml :

<style name="AppTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabTextAppearance">@style/YourTextAppareance</item>
</style>

Then set a YourTextAppareance style.

<style name="YourTextAppareance" parent="TextAppearance.Design.Tab">
    <item name="android:fontFamily">sans-serif</item>
</style>

Finally, set the style to your TabLayout :

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        style="@style/AppTabLayout"
        app:tabTextColor="#000"
        app:tabTextAppearance="@style/MineCustomTabText"
        app:tabGravity="fill"/>

Taken from this : TabLayout tab style

Using Custom Views

An alternative way to do this is to use custom views and setup your fonts in the layout of the custom view. But this is a more complex way to do this because you must handle the views when "selected" and "not selected".

public class SectionsPageAdapter  extends FragmentPageViewAdapter {

public SectionsPageAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public View getCustomView(int position, View v, boolean selected) {

    if (v == null) {
        LayoutInflater li = LayoutInflater.from(App.getApplication());
        v = li.inflate(R.layout.view_tab, null);
    }

    TextView textView = (TextView) v.findViewById(R.id.textView);
    // Change your font on the textview here.

    textView.setText(getPageTitle(position));

    // Take in account the selected var if you want another layout when
    // tab is selected.

    return v;
}

@Override
public Fragment getItem(int position) {
    // getItem is called to instantiate the fragment for the given page.
    if (position == 0)
        return Fragment.newInstance();
    else if (position == 1)
        return Fragment.newInstance();
    else
        return Fragment.newInstance();
}

@Override
public int getCount() {
    // Show 3 total pages.

    return 3;
}

@Override
public CharSequence getPageTitle(int position) {
    switch (position) {
        case 0:
            return "Tab 1";
        case 1:
            return "Tab 2";
        case 2:
            return "Tab 3";
    }
    return null;
}
}

Then, juste browse the list of your tabs and add the custom view.

for (int i=1; i < mSectionsPagerAdapter.getCount(); i++)
{
    tabLayout.getTabAt(i).setCustomView(mSectionsPagerAdapter.getCustomView(i, null, false));
}

Don't forget to check onPageSelected changes to update the views :

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
                if (i == position)
                    tabLayout.getTabAt(i).setCustomView(mSectionsPagerAdapter.getCustomView(i, tabLayout.getTabAt(i).getCustomView(), true));
                else
                    tabLayout.getTabAt(i).setCustomView(mSectionsPagerAdapter.getCustomView(i, tabLayout.getTabAt(i).getCustomView(), false));
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

For reminder, here it is how to change the font programmatically :

Typeface font=Typeface.createFromAsset(getAssets(), "fonts/DejaVuSerif-Italic.ttf");
newfont.setTypeface(font);
Community
  • 1
  • 1
doubotis
  • 219
  • 2
  • 10
  • can you refer how to this with a custom font please? – Anas Haxer Apr 17 '16 at 21:33
  • Not available on styles by default. If you supports only API7+, here is a library that seems to allow this [Calligraphy](https://github.com/chrisjenx/Calligraphy) – doubotis Apr 17 '16 at 21:40
  • i think that this library is broken i've been trying with it for 1 hour now and the app crashes everytime i use it :/ – Anas Haxer Apr 17 '16 at 23:27
  • A lot of librairies implement custom fonts on styles, just check it on github. In case of, I edited my post to present an alternative (but not optimal) way that should work without any additional librairies. – doubotis Apr 18 '16 at 07:05
  • i applied the calligraphy library so well but the it's applying for the toolbar and the fragmentseven for the navigation drawer but not for the tabs names! :( , thanks for helping so far ^^" – Anas Haxer Apr 18 '16 at 17:03
  • @AnasHaxer I'm working ona similar problem. Did you find a solution to this? If you did do share it. – Iffat Fatima Feb 19 '17 at 17:39