我不知道如何使TextView上的特定文本变成粗体。
是这样的
txtResult.setText(id+" "+name);
我希望输出是这样的:
1111年尼尔
id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。
我不知道如何使TextView上的特定文本变成粗体。
是这样的
txtResult.setText(id+" "+name);
我希望输出是这样的:
1111年尼尔
id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。
当前回答
我认为所选择的答案并没有提供一个令人满意的结果。我写了自己的函数,它有两个字符串;全文和要加粗的文本部分。
它返回一个SpannableStringBuilder,带有从'text'中粗体的'textToBold'。
我发现使子字符串加粗而不用标签包装的能力很有用。
/**
* Makes a substring of a string bold.
* @param text Full text
* @param textToBold Text you want to make bold
* @return String with bold substring
*/
public static SpannableStringBuilder makeSectionOfTextBold(String text, String textToBold){
SpannableStringBuilder builder=new SpannableStringBuilder();
if(textToBold.length() > 0 && !textToBold.trim().equals("")){
//for counting start/end indexes
String testText = text.toLowerCase(Locale.US);
String testTextToBold = textToBold.toLowerCase(Locale.US);
int startingIndex = testText.indexOf(testTextToBold);
int endingIndex = startingIndex + testTextToBold.length();
//for counting start/end indexes
if(startingIndex < 0 || endingIndex <0){
return builder.append(text);
}
else if(startingIndex >= 0 && endingIndex >=0){
builder.append(text);
builder.setSpan(new StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0);
}
}else{
return builder.append(text);
}
return builder;
}
其他回答
只需要在HTML中构建字符串并设置它:
String sourceString = "<b>" + id + "</b> " + name;
mytextview.setText(Html.fromHtml(sourceString));
如果粗体文本的位置是固定的(例如:如果是在textView的开始),然后使用两个不同的textView具有相同的背景。然后你可以使其他textView的textStyle为粗体。
与单个textView相比,这将需要两倍的内存,但速度会提高。
只需在标签中添加这个
dangerouslySetInnerHTML={{__html: "<p>Your html text here.<p>"}}
wtsang02答案是最好的方法,因为,Html.fromHtml("")现在已弃用。这里我要稍微加强一下,以方便那些在动态地将第一个单词加粗方面有问题的人,不管句子的大小。
首先让我们创建一个方法来获取第一个单词:
private String getFirstWord(String input){
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' '){
return input.substring(0, i);
}
}
return input;
}
现在假设你有一个像这样的长字符串:
String sentence = "friendsAwesomeName@gmail.com want's to be your friend!"
你希望你的句子是yourAwesomeName@gmail.com想成为你的朋友! 你所要做的就是-获取firstWord并获取它的长度以使firstWord加粗,就像这样:
String myFirstWord = getFirstWord(sentence);
int start = 0; // bold will start at index 0
int end = myFirstWord.length(); // and will finish at whatever the length of your first word
现在按照wtsang02的步骤来做,就像这样:
SpannableStringBuilder fancySentence = new SpannableStringBuilder(sentence);
fancySentence.setSpan(new android.text.style.StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(fancySentence);
就是这样!现在你应该可以在长句或短句中加粗任意大小的单词了。
简单的例子
在you strings.xml中
<string name="str_privacy_policy">This is our Privacy Policy.</string>
如果你想让“隐私政策”特别加粗,就在加粗标签之间加字符串。
像这样
<string name="str_privacy_policy">This is our <b>Privacy Policy.</b></string>
结果是
这是我们的隐私政策