2016-03-03 84 views
0

我想在我的应用程序中使用TabLayoutViewPager,但我想为TabLayout设置自定义字体,但我不能这样做!
我用这个代码:如何在Android中为TabLayout设置自定义字体?

Typeface droidSerifMonoTF = Typeface.createFromAsset(getAssets(), "fonts/DroidSerif.ttf"); 

for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
      TextView t = new TextView(this); 
      t.setText(mSectionsPagerAdapter.getPageTitle(i)); 
      t.setTypeface(droidSansMonoTF); 

      actionBar.addTab(actionBar.newTab() 
        .setCustomView(t) 
        .setTabListener(this)); 

     } 

从这个链接:Link但不工作我!
我该怎么办?

+0

任何错误即将到来或字体不适用? –

+1

您可以使用setCustomView()并在布局xml中为TextView定义字体,请参见:http://stackoverflow.com/questions/31698756/remove-line-break-in-tablayout –

+0

@DanielNugent,tnx我亲爱的朋友<3 –

回答

2

您可以通过扩展TabLayout类来实现。覆盖onLayout方法波纹管:

@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<tabCount; i++){ 
     tabView = (ViewGroup)tabStrip.getChildAt(i); 
     tabChildCount = tabView.getChildCount(); 
     for(int j=0; j<tabChildCount; j++){ 
      tabViewChild = tabView.getChildAt(j); 
      if(tabViewChild instanceof AppCompatTextView){ 
       if(fontFace == null){ 
        fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans)); 
       } 
       ((TextView) tabViewChild).setTypeface(fontFace, Typeface.BOLD); 
      } 
     } 
    } 
} 

必须覆盖onLayout的方法,因为,当您使用setupWithViewPager方法绑定与ViewPager的TabLayout,你必须设置标签的文本或者与的setText方法,或在PagerAdapter之后,当发生这种情况时,onLayout方法调用父ViewGroup(TabLayout),这是放置设置fontface的地方。(更改TextView文本导致调用它的父级的onLayout方法 - tabView有两个孩子,一个是ImageView另一个是TextView)

相关问题