android - 使用 ViewPager2 的自定义选项卡布局

标签 android android-tablayout android-viewpager2

我正在尝试通过 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/

相关文章:

java - LibGDX 日志记录未显示在 logcat 中

android - 当可见性从 GONE 变为 VISIBLE 时,TabLayout 文本消失

android - tablayout 中的选项卡不显示选项卡图标

android - MVVM:从内部 fragment 更新viewpager2的容器 View

android - 如何在 android 应用程序后台时隐藏 android 中的 View (不停止 android 在后台拍摄快照)

android - 牛轧糖上深色背景上的黑色文字(android.R.layout.simple_spinner_item)

android - TabLayout header 隐藏 fragment 中 ListView 上的第一项

android - 找不到 com.androidx.multidex :multidex:2. 0.1

android - 删除 viewPager2 中的 fragment 使用 FragmentStateAdapter,但仍显示

javascript - 强制移动屏幕键盘不是绝对位置?