带有不同textSize的TextView

这可能在一个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

尝试

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

我知道答案很晚,但人们仍然可能有同样的问题。即使我在这方面挣扎了很多。 假设你的strings.xml文件中有这两个string

  <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中为它们定义两个Style,并使用不同的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> 

现在从Java文件中,您需要使用spannable在单个textView中加载这两个样式和string

 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方法,它将在应用样式之后返回格式化的string

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

您始终可以使用Html类来parsing具有不同格式的html样式的string:您可以尝试如下所示:

 textView.setText(Html.fromHtml("<font size=\"5\" face=\"arial\" color=\"red\">" + "This paragraph is in Arial, size 5, and in red text color." + "</font>" + ...));