SpannableString和TextAppearanceSpan,仅应用颜色

时间:2018-06-08 13:40:35

标签: android textview

我希望在一个文本视图中有2个文本样式,所以我尝试

Spannable text = new SpannableString(pseudo + " " + "some text after that");
text.setSpan(new TextAppearanceSpan(mContext, R.style.PseudoStyle), 0, pseudo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new TextAppearanceSpan(mContext, R.style.TextStyle), pseudo.length() + 1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

holder.mText.setText(text);

在这里你可以找到我的风格

<style name="PseudoStyle">
  <item name="android:textAllCaps">true</item>
  <item name="android:textSize">14sp</item>
  <item name="android:textStyle">bold</item>
  <item name="android:textColor">@color/pink_light</item>
</style>
<style name="TextStyle">
  <item name="android:textColor">@color/white</item>
</style>

但是,只有android:textColor才适用。

你能用这种方法帮助其他风格吗?

由于

2 个答案:

答案 0 :(得分:0)

为什么不声明两个样式并将SpannableString中文本部分的当前样式应用于此(仅作为示例):

Spannable text = new SpannableString(pseudo + " " + "some text after that");
text.setSpan(new TextAppearanceSpan(mContext, R.style.PseudoStyle_1), 0, pseudo.length() - 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new TextAppearanceSpan(mContext, R.style.PseudoStyle_2), pseudo.length() - 10, pseudo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.mText.setText(text);

答案 1 :(得分:0)

我找到了一个棘手的解决方案,正常添加StyleSpan Bold而不是按样式添加

java:

text.setSpan(new TextAppearanceSpan(mContext, R.style.PseudoStyle), 0, pseudo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new StyleSpan(Typeface.BOLD), 0, pseudo().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new TextAppearanceSpan(mContext, R.style.TextStyle), pseudo.length() + 1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

xml:

<style name="PseudoStyle">
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">@color/pink_light</item>
</style>

<style name="TextStyle">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@color/white</item>
</style>