动态更改标签文本标题

时间:2017-01-05 10:07:41

标签: android

我有一个tablayout,在viewpager下有四个标签。我想在滑动标签时更改文字标题。我的问题是我无法分别处理标签。

例如,四个标签标题是1,2,3,4,当我滑动时,它将显示为1,9,3,4或1,2,9,4 ......

但在我的情况下是7,9,7,7或7,7,9,7 ...

我尝试在onTabUnselected函数上编写它。显然我没有变量来控制它。

接下来我该怎么办?

该计划的一部分:

private ViewPager viewPager;

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayoutHomePage));
        tabLayoutHomePage.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int id=tab.getPosition();
                switch (id){
                    case 0:
                        tab.setText("9");
                        break;
                    case 1:
                        tab.setText("9");
                        break;
                    case 2:
                        tab.setText("9");
                        break;
                    case 3:
                        tab.setText("9");
                        break;
                }
                    viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                int id=tab.getPosition();
                switch (id){
                    case 0:
                        tab.setText("7");
                        break;
                    case 1:
                        tab.setText("7");
                        break;
                    case 2:
                        tab.setText("7");
                        break;
                    case 3:
                        tab.setText("7");
                        break;
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        }); 

原始声明四个标签标题

tabLayoutHomePage = (TabLayout) view.findViewById(R.id.tabLayoutHomePage);
    tabLayoutHomePage.addTab(tabLayoutHomePage.newTab().setText(R.string.bloodPressure));
    tabLayoutHomePage.addTab(tabLayoutHomePage.newTab().setText(R.string.bloodSugar));
    tabLayoutHomePage.addTab(tabLayoutHomePage.newTab().setText(R.string.bodyWeight));
    tabLayoutHomePage.addTab(tabLayoutHomePage.newTab().setText(R.string.vaccine));
    tabLayoutHomePage.setTabGravity(TabLayout.GRAVITY_FILL);

2 个答案:

答案 0 :(得分:15)

试试这个

tabLayoutHomePage.getTabAt(position).setText("new Text");

答案 1 :(得分:0)

这也应该起作用

mSlidingTabLayout.setTabText(position,name)