Android标签 - 设置自定义视图问题

时间:2017-09-07 08:06:16

标签: 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.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));

但它让我只是第三个标签

enter image description here

现在,好奇的是,如果我尝试设置文本,如下所示:

tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

一切正常(文字被渲染)......但是我需要那个自定义视图,因为那个计数器。

有人可以解释一下为什么会这样吗?

3 个答案:

答案 0 :(得分:1)

打开 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);

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:1)

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

相关问题