Search code examples
androidlistviewtextstyles

How to bold specific word in listview android


I'm trying to bold the specific text in listview that contains ":". I want to bold the word underlined in the image below that contains ":" but I'm having trouble getting all the message. Please see my current code below. I appreciate for your any response.

enter image description here

ArrayList<String> list_items = new ArrayList<String>();
public  void listview_refresh(){
    arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);

    ContentResolver cResolver = getContentResolver();
    Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
    int indexBody = smsInboxCursor.getColumnIndex("body");
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
    do{
        str = smsInboxCursor.getString(indexBody) ;
        arrayAdapter.add(str);

        String[] separated = str.split(":");
        String separate = separated[1];

        arrayAdapter.replaceAll(separate, "<b>" + separate + "</b>"); //errorline

    }while (smsInboxCursor.moveToNext());
}

Solution

  • Add string as Html within the adapter list. I have modified your code and added Html.fromHtml(..) to make text to use HTML code within.

    ArrayList<String> list_items = new ArrayList<String>();
    public  void listview_refresh(){
    arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
    
    ContentResolver cResolver = getContentResolver();
    Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
    int indexBody = smsInboxCursor.getColumnIndex("body");
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
    do{
        str = smsInboxCursor.getString(indexBody) ;
        
        String[] separated = str.split(":");
        String separate = separated[1];
    
        str = str.replaceAll(separate, "<b>" + separate + "</b>"); //errorline
        arrayAdapter.add(Html.fromHtml(str));
    }while (smsInboxCursor.moveToNext());
    }