0

Here is the TextView that I am working with:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:singleLine="true"
        android:text="TextView for test only"
        android:textColor="#fff" />

</androidx.constraintlayout.widget.ConstraintLayout>

The default text color is white. My goal is to change the color of the first character to black and the background color of the first character to white. This is the code I am currently using:

TextView txt = (TextView) findViewById(R.id.txt);
SpannableStringBuilder sp = new SpannableStringBuilder(txt.getText());
sp.setSpan(new BackgroundColorSpan(Color.WHITE), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
sp.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
txt.setText(sp);

Everything functions as expected, with the exception of the background color of the first character. I need it to take up the full height of the TextView, not just the space between the text.

This is the current result:

enter image description here

And this is the desired outcome: (Created using Figma)

enter image description here

I hope this provides a clear understanding of my issue. Thank you for your help.

Taha Sami
  • 1,565
  • 1
  • 16
  • 43
  • why not create 2 textviews? – VipulSharma Jan 11 '23 at 07:13
  • @VipulSharma [As shown in this image](https://i.stack.imgur.com/qTiwA.jpg), I have created a news ticker similar to the one used by the Sky News channel. Everything functions as expected, except for the background behind the text "BREAKING NEWS". In the Sky News news ticker, the background takes up the full height of the view, but in my app, it does not. – Taha Sami Jan 11 '23 at 07:27

0 Answers0