2016-03-03 79 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)

相關問題