办法可以在TabLayout中使用SpannableString

办法可以在TabLayout中使用SpannableString

本文介绍了有什么办法可以在TabLayout中使用SpannableString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用两个不同的文本大小设置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!

我已经尝试过使用SpannableString,如下所示.该代码段位于for循环中,直到5 !!

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);

但是,正如CommonaSware所说的那样, setText()并没有吸收丰富的内容!

But as mentioned by CommonaSware setText() is not taking the rich content!

推荐答案

TabLayout的默认样式使用TextAppearance,并且textAllCaps属性设置为true.转换方法将CharSequence视为平坦的String,因此所有Spannable信息都会丢失.

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.

为防止这种情况,我们可以为TabLayout创建禁用textAllCaps的样式.例如:

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>

TabLayout上将其设置为tabTextAppearance将使您的SpannableString正常工作.

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" />


如评论中所述,在此处为选项卡使用自定义View是另一种选择,因为默认情况下该属性不会设置有问题的属性.


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.

这篇关于有什么办法可以在TabLayout中使用SpannableString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:04