I try to do that in the text displayed in TextView, it was "It is necessary to XXX rub." But XXX should be red.

I try this:

public void onButtonClick (View v) { TextView Total = (TextView) findViewById(R.id.result); float Sum = (Tank-FuelCurrent)*PriceFl; String sSum = String.format("%.0f", Sum); SpannableStringBuilder ssb = new SpannableStringBuilder(sSum); ssb.setSpan(new ForegroundColorSpan(Color.RED), 0, sSum.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Total.setText("Необходимо "+ssb+" руб."); } 

Prints the entire line in one default color. If I change to

 Total.setText(ssb); 

then, accordingly, only the price is displayed and displayed as it should, in red. I'm testing on a device with Android 4.2.2. How to correctly concatenate the result with a string?

    1 answer 1

    Use append

     private fun stylizationTextInfo(textView: TextView) { val result = SpannableStringBuilder() val ssb = SpannableStringBuilder("1000") val txtNeed = SpannableStringBuilder("Необходимо ") val txtMoney = SpannableStringBuilder(" руб.") ssb.setSpan(ForegroundColorSpan(Color.RED), 0, ssb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) result.append(txtNeed).append(ssb).append(txtMoney) textView.text = result } 

    java:

     private void stylizationTextInfo(TextView textView) { SpannableStringBuilder result = new SpannableStringBuilder(); SpannableStringBuilder ssb = new SpannableStringBuilder("1000"); SpannableStringBuilder txtNeed = new SpannableStringBuilder("Необходимо "); SpannableStringBuilder txtMoney = new SpannableStringBuilder(" руб."); ssb.setSpan(new ForegroundColorSpan(Color.RED), 0, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); result.append(txtNeed).append(ssb).append(txtMoney); textView.setText(result); } 

    enter image description here

    • one
      Yes, it happened. Thank! - IMD