2016-07-18 29 views
0

因爲這個代碼是重複的,我決定改變使用數組來簡化代碼

TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
tabOne.setText("ONE"); 
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0); 
tabLayout.getTabAt(0).setCustomView(tabOne); 

TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
tabTwo.setText("TWO"); 
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_call, 0, 0); 
tabLayout.getTabAt(1).setCustomView(tabTwo); 

TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
tabThree.setText("THREE"); 
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_contacts, 0, 0); 
tabLayout.getTabAt(2).setCustomView(tabThree); 

分爲:

private void SetupTab() { 
    TextView[] Tab = new TextView[3]; 
    int[] tabIcons = { 
     R.drawable.tab1, 
     R.drawable.tab2, 
     R.drawable.tab3 
    }; 
    String[] tabTitle = {"ONE","TWO","THREE"}; 

    for (int i = 0; i < 3; i++) { 
     TextView Tab[i] = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
     Tab[i].setText(tabTitle[i]); 
     Tab[i].setCompoundDrawablesWithIntrinsicBounds(0, tabIcons[i], 0, 0); 
     tabLayout.getTabAt(i).setCustomView(Tab[i]); 
    } 
} 

,但我得到了我的程序不工作的問題。任何人都可以幫我解決它嗎?我非常感謝你的幫助。

+2

你繪製資源是不一樣的 –

+1

你是什麼意思你的程序不能正常工作?該SetupTab方法是否被調用? –

+0

對不起,我錯了我錯誤輸入了繪圖。謝謝你告訴我這件事。 – helloworld

回答

0

我認爲TextView[] Tab是不必要的:

private void SetupTab() { 
    int[] tabIcons = { 
      R.drawable.tab1, 
      R.drawable.tab2, 
      R.drawable.tab3 
    }; 
    String[] tabTitle = {"ONE","TWO","THREE"}; 

    for (int i = 0; i < 3; i++) { 
     TextView view = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
     view.setText(tabTitle[i]); 
     view.setCompoundDrawablesWithIntrinsicBounds(0, tabIcons[i], 0, 0); 
     tabLayout.getTabAt(i).setCustomView(view); 
    } 
} 
+0

這是迄今爲止最好的解決方案:D非常感謝:D – helloworld