【问题标题】:Android tabs - set custom view issueAndroid标签 - 设置自定义视图问题
【发布时间】:2018-02-15 21:13:01
【问题描述】:

我正在尝试使用自定义视图制作一些标签。这是我的代码

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("Tab 1")); tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

一切正常(文本被渲染)......但由于那个计数器,我需要那个自定义视图。

谁能解释一下为什么会这样?

【问题讨论】:

  • 你设置了 1 TextView tabText 3 次,最后一个是“Tab 3”,这可能就是它保持不变的原因......

标签: android android-tablayout


【解决方案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】:

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

    【讨论】:

      【解决方案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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-16
        相关资源
        最近更新 更多