Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display icons on FragmentPagerAdapter tabs

This example is created in Xamarin using C#, if you know the answer in Java, I'll be able to convert it into C# too

I'm using the FragmentPagerAdapter to display three different Fragments as Tabs. I'm able to display some text in the Tab headers like this:

public override Java.Lang.ICharSequence GetPageTitleFormatted(int position)
{
    return new Java.Lang.String("Tab: " + position);
}

This works just fine: I'm seeing three tabs with titles Tab: 0, Tab: 1 and Tab: 2.

Now, I want to replace the text with some icons. I'm trying to do that the same was as with the PagerSlidingTabStrip, using a SpannableString & ImageSpan .

public override Java.Lang.ICharSequence GetPageTitleFormatted(int position)
{
    var image = Application.Context.Resources.GetDrawable(Resource.Drawable.icon);
    image.SetBounds(0, 0, image.IntrinsicWidth, image.IntrinsicHeight);

    var spannableString = new Android.Text.SpannableString("[icon]");
    var imageSpan = new Android.Text.Style.ImageSpan(image, Android.Text.Style.SpanAlign.Bottom);
    spannableString.SetSpan(imageSpan, 0, 1, Android.Text.SpanTypes.ExclusiveExclusive);
    return spannableString;
}

Sadly, what I'm seeing right now is three times [icon] as headers. It looks like as if the icons aren't added to the headers at all.

Am I doing something wrong here? Thanks for any help!

like image 674
MarcoK Avatar asked Sep 25 '15 09:09

MarcoK


1 Answers

By default, the tab created by TabLayout sets the textAllCaps property to be true, which prevents ImageSpans from being rendered. You can override this behavior by changing the tabTextAppearance property.

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
      <item name="tabTextAppearance">@style/MyCustomTextAppearance</item>
</style>

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

Then you can add the MyCustomTabLayout Style to your TabLayout like this:

<android.support.design.widget.TabLayout
 android:id="@+id/tabs"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 style="@style/MyCustomTabLayout" />
like image 112
Youp Hulsebos Avatar answered Sep 19 '22 10:09

Youp Hulsebos