Using TabLayout inside a Fragment; tab text invisible

夙愿已清 提交于 2019-11-28 05:01:18

I face the same problem with new version of android support Design Library v23.1.1. But I just figure it out what happening.

if your view pager has 2 fragment as your mention above, then you set your view pager with this statement:

tabLayout.setupWithViewPager(viewPager);

automatically you will have 2 tabs with empty text. So you should not add new tab anymore. But something you have to do is to set text in that two created tabs.

tabLayout.getTabAt(0).setText("Campusplan");
tabLayout.getTabAt(1).setText("Raumplan");

Conclusion. To make tabs work as you want, important thing you have to do :

tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setText("Campusplan");
tabLayout.getTabAt(1).setText("Raumplan");

I hope this will be helpful for you :)

Update: Design Library v23.0.0 solves this issue.


Found the problem here: https://code.google.com/p/android/issues/detail?id=180462

Simple workaround:

tabLayout.post(new Runnable() {
    @Override
    public void run() {
        tabLayout.setupWithViewPager(viewPager);
    }
});

just tried to override the method in adapter:

public CharSequence getPageTitle(int position) {}

and it works.

The developer working on this library recommends the following work-a-round:

if (ViewCompat.isLaidOut(tabLayout)) {
        tabLayout.setupWithViewPager(viewPager);
    } else {
        tabLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                tabLayout.setupWithViewPager(viewPager);
                tabLayout.removeOnLayoutChangeListener(this);
            }
        });
    }

Lack reputation to comment @arif ardiansyah...

Check the source code:

 `TabLayout#setupWithViewPager(...)` 

 -->>`setPagerAdapter(adapter, true);`

 -->>`populateFromPagerAdapter();`

Here, TabLayout removes all tabs and recreates some new tabs whose text are set with PagerAdapter#getPageTitle(...). So you can override this method to provide Tablayout with your tabs' title.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!