Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any-way to use SpannableString in TabLayout?

I want to set the title of the TabLayout with two different text sizes. Like the given image below. Or the other way around to achieve this!

enter image description here

I have tried with SpannableString like give below. This snippet is in the for loop till 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 by CommonaSware setText() is not taking the rich content!

like image 673
android_griezmann Avatar asked Nov 30 '16 11:11

android_griezmann


People also ask

What is SpannableString?

↳ android.text.SpannableString. This is the class for text whose content is immutable but to which markup objects can be attached and detached.

What is a tabLayout in Android?

In Android TabLayout is a new element introduced in Design Support library. It provides horizontal layout to display tabs on the screen. We can display more screens in a single screen using tabs. We can quickly swipe between the tabs.


2 Answers

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.

like image 93
Mike M. Avatar answered Oct 03 '22 22:10

Mike M.


Another approach is to use SpannableString text to TabLayout:

@Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        SpannableString sb = new SpannableString( tabTitles[position]);
        sb.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size
        sb.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color

        return sb;
    }

For more information check Add Icons+Text to TabLayout

like image 31
VIISHRUT MAVANII Avatar answered Oct 03 '22 22:10

VIISHRUT MAVANII