不同字体大小的TextView

90

在一个TextView中,是否可以设置不同的textSize?我知道可以使用以下方法更改文本样式:

TextView textView = (TextView) findViewById(R.id.textView);
Spannable span = new SpannableString(textView.getText());
span.setSpan(arg0, 1, 10, arg3);
textView.setText(span)

我知道要改变大小的文本范围起始和结束位置。但是我应该使用什么作为arg0arg3呢?

3个回答

201

请尝试

span.setSpan(new RelativeSizeSpan(0.8f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

1
它看起来没问题,但是不起作用。我的TextView中的整个文本始终具有相同的大小。 - woyaru
1
在 setSpan() 之后,我应该将 span 应用(更新)到我的 TextView 吗? - woyaru
4
抱歉我留了三个评论,但是我已经解决了这个问题。只需要:textView.setText(span) - woyaru
你知道怎么将大小和颜色结合起来应用到span标签吗? - Ionut Negru

24

我知道回答很晚,但人们可能仍然会有相同的问题。即使我为此付出了很多努力。 假设您在strings.xml文件中有这两个字符串

 <string name="my_text">You will need a to complete this assembly</string>
 <string name="text_sub1">screwdriver, hammer, and measuring tape</string>

现在您需要在style.xml中为它们定义两种样式,使用不同的textSize。

<style name="style0">
    <item name="android:textSize">19sp</item>
    <item name="android:textColor">@color/standout_text</item>
    <item name="android:textStyle">bold</item>
</style>
<style name="style1">
    <item name="android:textSize">23sp</item>
    <item name="android:textColor">@color/standout_light_text</item>
    <item name="android:textStyle">italic</item>
</style>

现在,您需要使用 Spannable 将这两种样式和字符串加载到单个 textView 中。
SpannableString formattedSpan = formatStyles(getString(R.string.my_text), getString(R.string.text_sub0), R.style.style0, getString(R.string.main_text_sub1), R.style.style1);
textView.setText(formattedSpan, TextView.BufferType.SPANNABLE);

以下是 formatStyles 方法,它将在应用样式后返回格式化的字符串。
private SpannableString formatStyles(String value, String sub0, int style0, String sub1, int style1)
{ 
    String tag0 = "{0}";
    int startLocation0 = value.indexOf(tag0);
    value = value.replace(tag0, sub0);

    String tag1 = "{1}";
    int startLocation1 = value.indexOf(tag1);
    if (sub1 != null && !sub1.equals(""))
    { 
        value = value.replace(tag1, sub1);
    } 
    SpannableString styledText = new SpannableString(value);
    styledText.setSpan(new TextAppearanceSpan(getActivity(), style0), startLocation0, startLocation0 + sub0.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (sub1 != null && !sub1.equals(""))
    { 
        styledText.setSpan(new TextAppearanceSpan(getActivity(), style1), startLocation1, startLocation1 + sub1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } 

    return styledText;
}

14

试试使用 AbsoluteSizeSpan

snackbarText.setSpan(new AbsoluteSizeSpan(fontsize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

完整的代码如下:

SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Your text");
snackbarText.setSpan(new AbsoluteSizeSpan(fontsize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar.make(getCurrentFocus(), snackbarText, Snackbar.LENGTH_LONG).setAction("Action", null).show();`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接