I am trying to use custom tabs for my ViewPager2 via the TabLayout.Tab.setCustomView method. But it doesn't work.
Here is a code snippet from my Activity for preparing the ViewPager2 with a TabLayout:
@Override
protected void onCreate(Bundle savedInstanceState)
{
...
mMyViewPager2 = findViewById(R.id.view_pager);
mMyViewPager2.setAdapter(new MyPagerAdapter(this));
mMyTabLayout = findViewById(R.id.media_tab);
new TabLayoutMediator(mMyTabLayout, mMyViewPager2, myTabHandler).attach();
}
private class MyPagerAdapter extends FragmentStateAdapter
{
...
}
And here is the code snippet for my TabLayoutMediator.TabConfigurationStrategy (also inside my Activity):
private TabLayoutMediator.TabConfigurationStrategy myTabHandler = new TabLayoutMediator.TabConfigurationStrategy()
{
private TextView tabTitle;
private TextView tabSubtitle;
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position)
{
View tabView = LayoutInflater.from(MyActivity.this).inflate(R.layout.tab_layout, null, false);
tabTitle = tabView.findViewById(R.id.tab_title);
tabSubtitle = tabView.findViewById(R.id.tab_subtitle);
tabTitle.setText("Title" + (position + 1));
tabSubtitle.setText("Subtitle" + (position + 1));
tab.setCustomView(tabView);
}
}
But with the above setup, the tabs remain blank.
I've also tried the following approach in my TabConfigurationStrategy (from this post); but it doesn't work, either:
FrameLayout frameLayout = new FrameLayout(MyActivity.this);
frameLayout.addView(tabView);
I'd like to know what is wrong with my code, and how can I correct it to show custom tab layouts with ViewPager2.