Search code examples
androidandroid-listview

How to make part of the text Bold in android at runtime?


A ListView in my application has many string elements like name, experience, date of joining, etc. I just want to make name bold. All the string elements will be in a single TextView.

my XML:

<ImageView
    android:id="@+id/logo"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="15dp" >
</ImageView>

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/logo"
    android:padding="5dp"
    android:textSize="12dp" >
</TextView>

My code to set the TextView of the ListView item:

holder.text.setText(name + "\n" + expirience + " " + dateOfJoininf);

Solution

  • Let's say you have a TextView called etx. You would then use the following code:

    final SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");
          
    final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
    final StyleSpan iss = new StyleSpan(android.graphics.Typeface.ITALIC); //Span to make text italic
    sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold 
    sb.setSpan(iss, 4, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
    
    etx.setText(sb);