0

I have a textview where I concat two strings, I wan the first string alone to be in different color.

        tvMobileNo.text = "Mobile Number :   " + sharedPreferences.getString("mobile_number", "")
        tvEmail.text = "Email :   " + sharedPreferences.getString("email", "")
        tvAddress.text = "Address :   " + sharedPreferences.getString("address", "")

In this I only want the first string(""Mobile number", "Email","Address") to be of different color.

ADM
  • 20,406
  • 11
  • 52
  • 83
yazhini
  • 57
  • 1
  • 6

3 Answers3

0

TextView supports some html tags.

String htmlText = "<font color='#ff0000'>Mobile Number:</font> 123456";
tvMobileNo.setText(Html.fromHtml(htmlText));
AIMIN PAN
  • 1,563
  • 1
  • 9
  • 13
0

Use SpannableString to complete your needs. Here I set the string whose id is restartAllEquipmentTvtextView string index from 3 to 5 to red

restartAllEquipmentTv.text = SpannableString(getString(R.string.restart_and_factory_reset_setting_restart_content)).setSpan(ForegroundColorSpan(Color.RED), 3, 5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE).toString()
Future Deep Gone
  • 831
  • 6
  • 16
-1

Make common funtion for convert your string spannable like this.

//pass param textviewid ,start,end,string
//R.color.Red it's your color you can change it as requirement

fun SpannableStringWithColor(view: TextView,start:Int,end:Int, s: String) {
    val wordtoSpan: Spannable =
        SpannableString(s)
    wordtoSpan.setSpan(
        ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.Red)),
        start,
        end,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    view.text = wordtoSpan
    }

In your case you can easy do it like this.

 SpannableStringWithColor(tvMobileNo,0,14,"Mobile Number :   " + sharedPreferences.getString("mobile_number", ""))

 SpannableStringWithColor(tvEmail,0,5,"Email :   " + sharedPreferences.getString("email", ""))

 SpannableStringWithColor(tvAddress,0,8,"Address :   " + sharedPreferences.getString("address", ""))
Umesh Yadav
  • 1,042
  • 9
  • 17