[android]使用数组来简化代码

发布时间: 2016/9/16 12:55:48
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

因为这段代码是重复的我决定去改变它

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]);
    }
}

后来我的程序不工作的问题。谁能帮我解决这个问题吗?我非常感激你的帮助。

解决方法 1:

我认为 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);
    }
}
官方微信
官方QQ群
31647020