Android选项卡-设置自定义视图问题

Android选项卡-设置自定义视图问题,android,android-tablayout,Android,Android Tablayout,我正在尝试使用自定义视图制作一些选项卡。这是我的密码 View tabContent = LayoutInflater.from(this).inflate(R.layout.tab_content, null); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); TextView tabText = (TextView) tabContent.findViewById(R.id.tabText); tabText.setTe

我正在尝试使用自定义视图制作一些选项卡。这是我的密码

View tabContent = LayoutInflater.from(this).inflate(R.layout.tab_content, null);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TextView tabText = (TextView) tabContent.findViewById(R.id.tabText);

tabText.setText("Tab 1");
tabLayout.addTab(tabLayout.newTab().setCustomView(tabContent));

tabText.setText("Tab 2");
tabLayout.addTab(tabLayout.newTab().setCustomView(tabContent));

tabText.setText("Tab 3");
tabLayout.addTab(tabLayout.newTab().setCustomView(tabContent));
但这只是我的第三个标签

现在,有趣的是,如果我试着只设置文本,如下所示:

tabLayout.addTab(tabLayout.newTab().setText(“tab1”));
tabLayout.addTab(tabLayout.newTab().setText(“tab2”));
tabLayout.addTab(tabLayout.newTab().setText(“Tab 3”))

一切正常(文本已呈现)。。。但我需要那个自定义视图,因为那个计数器


有人能解释一下为什么会发生这种情况吗?

打开Activity.java并修改和设置选项卡,如下面的代码所示

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 tab2 = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tab2.setText("TWO");
tab2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
tabLayout.getTabAt(1).setCustomView(tab2);

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

试试这个:

View tabContent = LayoutInflater.from(this).inflate(R.layout.tab_content, null);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TextView tabText1 = (TextView) tabContent.findViewById(R.id.tabText);
TextView tabText2 = (TextView) tabContent.findViewById(R.id.tabText);
TextView tabText3 = (TextView) tabContent.findViewById(R.id.tabText);

tabText1.setText("Tab 1");
tabLayout.getTabAt(0).setCustomView(tabText1);

tabText2.setText("Tab 2");
tabLayout.getTabAt(1).setCustomView(tabText2);

tabText3.setText("Tab 3");
tabLayout.getTabAt(2).setCustomView(tabText3);

需要将
tabContent
3次充气,因为
setCustomView()
方法直接作用于该实例,因此对
tabContent
对象的每次修改都会影响其余选项卡

您将设置1
TextView tabText
3次,最后一次是“Tab 3”,这可能就是为什么它会一直。。。