结交TextView中字符串的一部分大胆 [英] Making part of a string bold in textview

查看:120
本文介绍了结交TextView中字符串的一部分大胆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下code不工作?它的工作原理举杯,但没有一个TextView。 boldName不显示为粗体,当我运行我的程序,但它确实显示为粗体,当我将它设置为一个吐司。没有人有任何其他的解决方案?

 字符串boldName =< B>中+姓名+< / B>中;
跨区conBold = Html.fromHtml(boldName);
chosen_contact.setText(你选择了+ conBold +您的联系方式。);
 

解决方案

我真的不知道到底为什么TextViews的行为,他们做的方式在这里你可以设置这一切大胆,你是干什么的,但前提是他们整个的TextView是大胆的,但你不能,如果只是其中的一部分就是大胆,里面还有其他的字符串。

然而,这code会为你工作:

  //包含文本显示SpannableStringBuilder
SpannableStringBuilder SB =新SpannableStringBuilder(你选择了+姓名+您的联系方式。);

//创建一个大胆的StyleSpan要在SpannableStringBuilder使用
StyleSpan B =新StyleSpan(android.graphics.Typeface.BOLD); //跨度,使文本加粗

在SpannableStringBuilder的//只设置的名称部分要大胆 - > 16,16 + name.length()
sb.setSpan(二,16个,16 + name.length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE); //使第4个字符粗体

chosen_contact.setText(某人); //设置的TextView是SpannableStringBuilder
 

Why is the following code not working? It works in a Toast but not in a TextView. boldName doesn't show up as bold when I run my program but it does show up as bold when I set it to a Toast. Does anyone have any other solutions?

String boldName = "<b>" + name + "</b>";
Spanned conBold = Html.fromHtml(boldName);
chosen_contact.setText("You have chosen " + conBold + " as your contact.");

解决方案

I'm honestly not sure why exactly TextViews act the way they do where you can set it all bold as you are doing, but only if they entire TextView is bold, yet you can't if only part of it is bold and there are other Strings in there.

However, this code will work for you:

// a SpannableStringBuilder containing text to display
SpannableStringBuilder sb = new SpannableStringBuilder("You have chosen " + name + " as your contact.");

// create a bold StyleSpan to be used on the SpannableStringBuilder
StyleSpan b = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold

// set only the name part of the SpannableStringBuilder to be bold --> 16, 16 + name.length()
sb.setSpan(b, 16, 16 + name.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold

chosen_contact.setText(sb); // set the TextView to be the SpannableStringBuilder

这篇关于结交TextView中字符串的一部分大胆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆