how to have bold and normal text in same textview in android?

前端 未结 7 1178
终归单人心
终归单人心 2021-02-18 23:48

I have searched internet and tried the following code but its not working

SpannableString ss1 = new SpannableString(\"Health: \");
           ss1.setSpan(new and         


        
相关标签:
7条回答
  • 2021-02-19 00:20

    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)
    
    0 讨论(0)
  • 2021-02-19 00:25

    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);
    
    0 讨论(0)
  • 2021-02-19 00:28

    I think you should use 2 different textView, a label and one for the data. it's common and good practice

    0 讨论(0)
  • 2021-02-19 00:32

    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);
    }
    
    0 讨论(0)
  • 2021-02-19 00:33

    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
    
    0 讨论(0)
  • 2021-02-19 00:40

    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.

    0 讨论(0)
提交回复
热议问题