Custom sized italic Font using Spannable

2019-07-18 02:47发布

There is the following code:

String s = message + "\n" + date;
Spannable f = Spannable.Factory.getInstance().newSpannable(s);
f.setSpan(new ForegroundColorSpan(Color.BLUE), 0, message.length(), 0);
f.setSpan(new ForegroundColorSpan(Color.RED), message.length() + 1, s.length(), 0);

textView.setText(f);

This code works fine for setting up diffent colors for textView. But I need another feature - I'd like that "date" has got smaller size of font and italic typeface. How can I achieve that?

4条回答
我命由我不由天
2楼-- · 2019-07-18 03:17

You can make use of Html.fromHtml("your html string"), to do any style you want in HTML and then show it in the textview as shown below:

 Spanned htmlText = Html.fromHtml(getString(R.string.yourStringResource));
 yourTextView.setText(htmlText, TextView.BufferType.SPANNABLE);

And the XML string.xml, must have the string declared as shown below:

 <string name="yourStringResource"><![CDATA[BLA BLA BLA BLA <br/> BLABA <font color="blue" size="6">COLORED HTML</font>]]></string>

Hope this helps.

Regards!

查看更多
Luminary・发光体
3楼-- · 2019-07-18 03:21

You can use HTML tags, like this:

String s = "<html>" + message + "<br /><i><small>" + date + "</i></small></html>";
查看更多
放我归山
4楼-- · 2019-07-18 03:25

Yes, that is absolutely possible. You can simply add another Span:

Spannable.setSpan(new StyleSpan(Typeface.ITALIC), from, to, 0);
Spannable.setSpan(new RelativeSizeSpan(float size), from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

In this case, its a StyleSpan to Italic and a RelativeSizeSpan.

查看更多
smile是对你的礼貌
5楼-- · 2019-07-18 03:36

Check this

Different font size of strings in the same TextView

Try the below

String title="My Custom Text!";  
TextView tv = (TextView) findViewById(R.id.some_id);
SpannableString ss1=  new SpannableString(title);
ss1.setSpan(new StyleSpan(Typeface.ITALIC), 0, ss1.length(), 0);
ss1.setSpan(new RelativeSizeSpan(2f), 0, ss1.length, 0); 
tv.setText(ss1);

For more styling

http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring

查看更多
登录 后发表回答