How do I get the view of a Tab in a TabLayout?

NSouth picture NSouth · Oct 20, 2015 · Viewed 21.8k times · Source

I'd like to find the view of a Tab in a TabLayout so that I can pass it to another function. I'm not sure how to go about finding the view. myTabLayout.getTabAt(0).getCustomView() returns null.

How do I get the view?

TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout_main);
tabLayout.addTab(tabLayout.newTab().setText("Page1"));
tabLayout.addTab(tabLayout.newTab().setText("Page2"));

viewPager = (ViewPager) rootView.findViewById(R.id.pager_main);
pagerAdapter = new MyPagerAdapter(getActivity(), getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);

Answer

NSouth picture NSouth · Oct 22, 2015

I ended up using the following to get tab views. I'm just not sure if it's best practice or if it's reliable across all Android versions:

mainTab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(desiredPosition);

Looking at source we can see that tabLayout.getChildAt(0) returns the SlidingTabStrip which is an internal class extending LinearLayout that holds the tab views. Then, you can access the tab view with .getChildAt(desiredPosition). Note that when using getChildAt() boundaries are not being checked, so make sure you are calling correct indexes and also check for null returns.