I have searched internet and tried the following code but its not working
SpannableString ss1 = new SpannableString(\"Health: \");
ss1.setSpan(new and
Below I have mentioned the code which one through you can create spannableString in Kotlin
val spannableStringBuilder = SpannableStringBuilder()
val boldSpan: StyleSpan = StyleSpan(Typeface.BOLD)
sp_text.setSpan(boldSpan, firstIndex, lastIndex,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
sp_text.setSpan(clickableSpan, firstIndex, lastIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
sp_text.setSpan(ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorPrimary)), firstIndex, lastIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
I would use a string resource such as this:
<string name="health_status"><b>Health:</b> %1$s</string>
When you want to set the health status just use this code:
String ss1 = getString(R.string.health_status, strhealth);
I think you should use 2 different textView, a label and one for the data. it's common and good practice
I am bit late to answer, but I created a method for easy use by using answer already provided here.
private void setSpanString(String string1, String string2, TextView textView) {
SpannableStringBuilder builder=new SpannableStringBuilder();
SpannableString txtSpannable= new SpannableString(string1);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
txtSpannable.setSpan(boldSpan, 0, string1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(txtSpannable);
builder.append(string2);
textView.setText(builder, TextView.BufferType.SPANNABLE);
}
In kotlin, you can do this. I used this to bold characters/word within a string. For example:
item = "Philippines"
query = "Phil"
result = Philippines
val spannable = SpannableString(item)
val indexStart = item.indexOf(query)
val indexEnd = indexStart + query.length
spannable.setSpan(StyleSpan(Typeface.BOLD), indexStart, indexEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
and use it like this
textView.text = spannable
The easiest way is
textview1.setText(Html.fromHtml("<b>Health:</b> good"));
The mistake in your code is to use string concatenation here: "\n"+ss1+strhealth+"\n\n"
which strips out all formatting because the components are taken as normal strings.