我正在尝试通过 TabLayout.Tab.setCustomView
方法为我的 ViewPager2
使用自定义选项卡。但它不起作用。
这是我的 Activity
中的一段代码 fragment ,用于使用 TabLayout
准备 ViewPager2
:
@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
{
...
}
这是我的 TabLayoutMediator.TabConfigurationStrategy
的代码 fragment (也在我的 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);
}
}
但使用上述设置后,选项卡仍为空白。
我还在我的 TabConfigurationStrategy
中尝试了以下方法(来自 this post );但它也不起作用:
FrameLayout frameLayout = new FrameLayout(MyActivity.this);
frameLayout.addView(tabView);
我想知道我的代码有什么问题,以及如何更正它以使用 ViewPager2
显示自定义选项卡布局。
最佳答案
来自 setCustomView()
文档:
If the provided view contains a TextView with an ID of text1 then that will be updated with the value given to setText(CharSequence)
因此尝试将 tabTitle 的 Id 更改为 "@android:id/text1"
。
现在对于副标题,我不确定。使用"@android:id/text2"
可能值得一试。注意:"@android:id/text2"
存在。
不过,您可以通过声明方式将自己的布局应用到 TabItems
使用 android:layout=""
,因此您无需以编程方式执行此操作。 TabLayout
中有一个声明版本的示例 documentation .所以我相信这样的事情会奏效:
<TabLayout
...>
<TabItem
....
android:layout="@layout/linearLayout_tabitem_1"/>
<TabItem
....
android:layout="@layout/linearLayout_tabitem_2"/>
</TabLayout>
关于android - 使用 ViewPager2 的自定义选项卡布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65078252/