Is there a way to use SpannableString in TabLayout?

I want to set the TabLayout header with two different text sizes. Like this image below. Or vice versa, to achieve this!

enter image description here

I tried using SpannableString as below. This snippet is in a for loop until 5!

SpannableString mSpannableString= new SpannableString(s); mSpannableString.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size mSpannableString.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color mTabLayout.getTabAt(i).setText(mSpannableString); 

But, as mentioned in CommonaSware setText () , you are not getting rich content!

+5
source share
2 answers

TabLayout default style for TextView uses TextAppearance with the textAllCaps attribute set to true . The conversion method for this treats CharSequence as a flat String , so any Spannable information is lost.

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

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

Setting this parameter as tabTextAppearance to 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 the comments, using a custom View for tabs is another option, since by default this option will not have a problem attribute.

+6
source

Additional answer by Mike M.

I had the same problem, but only in Lollipop and in the opposite direction, in Oreo it worked just fine before styling it, fortunately, Mike solved it.

I used 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, this widget does not need to be styled if you work on Oreo and beyond.

0
source

Source: https://habr.com/ru/post/1260582/


All Articles