is there any-way to use SpannableString in TabLayout?

别来无恙 提交于 2019-12-01 17:46:55

TabLayout's default style for its TextViews uses a TextAppearance with the textAllCaps attribute set to true. The transformation method for this handles the CharSequence as a flat String, so any Spannable info is lost.

To prevent this, we can create a style for the TabLayout that disables textAllCaps. For example:

<style name="TabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="textAllCaps">false</item>
</style>

Setting this as the tabTextAppearance on the TabLayout will allow your SpannableString to work as expected.

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabTextAppearance="@style/TabTextAppearance" />

As mentioned in comments, using a custom View for the tabs is another option here, since that wouldn't have the problematic attribute setting by default.

Supplementary for Mike M. ´s Answer

I had the same issue but only in Lollipop and backwards , in Oreo it worked just fine before getting styled, fortunatelly Mike's answer solved it.

I was using Google Material TabLayout:

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/TabTextAppearance"
        android:background="@color/colorDarkGreen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:tabMaxWidth="0dp"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabBackground="@drawable/tab_color_selector_green">

</com.google.android.material.tabs.TabLayout>

At least, with this widget is not necessary to put styling if You are working for Oreo and on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!