【问题标题】:TabLayout - multiline tab title with iconTabLayout - 带有图标的多行标签标题
【发布时间】:2021-05-21 00:18:15
【问题描述】:

在选项卡上,我需要一个图标和一个或两行文本,具体取决于其长度。只要我没有图标,一切都会按预期工作。适合一行的标题显示在一行中,不占用两行的标题。当我添加一个图标时,文本开始被强制排成一行(更不用说它被剪裁在左侧)。请看下面的对比图:

如果不创建自定义选项卡布局,我可以在图标出现时实现多行文本效果吗?

我的代码:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabInlineLabel="true"
        app:tabMaxWidth="150dp"
        app:tabMode="scrollable"/>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
    tab.text = "Long text which takes multiple lines"
    tab.icon = ContextCompat.getDrawable(requireContext(), R.drawable.ic_add)
}.attach()

【问题讨论】:

    标签: android android-tablayout android-viewpager2


    【解决方案1】:

    您可以为您的标签项设置自定义View:

    1. 为您的自定义标签项创建布局View。

    2. 膨胀、绑定数据,并将此自定义 View 设置为您的标签:

      TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
          val tabItemLayout = layoutInflater.inflate(R.layout.my_tab_item, null).apply {
              findViewById<ImageView>(R.id.tab_icon_imageView).setImageSource(R.drawable.ic_add)
              findViewById<TextView>(R.id.tab_title_imageView).text = "Long text which takes multiple lines"
          }
      
          tab.customView = tabItemLayout 
      }.attach()
      

    【讨论】:

    • 问题是我是否可以在不创建自定义布局的情况下实现它。我已经有一个自定义布局的解决方法:)
    • @suue 对不起,我的错。但似乎没有其他办法......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2019-05-28
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多