Change the font of tab text in android design support TabLayout

前端 未结 18 1676
执念已碎
执念已碎 2020-11-27 13:38

I\'m trying to work on the new TabLayout from the android design library.

I want to change tab text to custom font. And,I tried to sear

18条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 14:14

    As Andrei answered, you can change fontface by extending TabLayout class. And as Penzzz said, you can't do it in addTab method. Override onLayout method as bellow:

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom){
        super.onLayout(changed, left, top, right, bottom);
    
        final ViewGroup tabStrip = (ViewGroup)getChildAt(0);
        final int tabCount = tabStrip.getChildCount();
        ViewGroup tabView;
        int tabChildCount;
        View tabViewChild;
    
        for(int i=0; i

    Must Overwrite onLayout method, because, when you use setupWithViewPager method to bind the TabLayout with the ViewPager, you have to set tabs text either with setText method or in the PagerAdapter after that and when this happened, onLayout method get called on the parent ViewGroup (TabLayout) and that's the place to put setting fontface.(Changing a TextView text cause calling onLayout method of it's parent - A tabView has two children, one is ImageView another is TextView)

    Another Solution:

    First, these lines of code:

        if(fontFace == null){
            fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
        }
    

    In above solution, should be written outside of two loops.

    But better solution for API >= 16 is using android:fontFamily:

    Create a Android Resource Directory named font and copy your desired font to the directory.

    Then use these styles:

    
    
    
    

提交回复
热议问题