2

I've got a simple TextView with a lightgreen background:

<TextView
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:background="@color/lightgreen"
/>

Basically I am using this TextView as a custom "overview/progressbar". Thus, I want to change the background in the different colors.

For example:

0%-25% of width = light green color

25%-66% of width = yellow color

66%-100% of width = red color

So instead looking like this:

enter image description here
It should look like this:

enter image description here

Is there any good solution doing this?

I've tried using different Segment ProgressBar libraries, however none of them had the option to set the percentage times of the color "dividers"

Savan Luffy
  • 440
  • 3
  • 12

2 Answers2

1

You can do this using the ClipDrawable. Create a layer-list (LayerDrawable) with the list of progress layers like:

progress_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <clip android:drawable="@color/red" />
    </item>
    <item>
        <clip android:drawable="@color/yellow" />
    </item>
    <item>
        <clip android:drawable="@color/green" />
    </item>
</layer-list>

and use it as the background of a TextView.

<TextView
    android:id="@+id/progress_text_view"
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:background="@drawable/progress_bg" />

To apply progress values:

private static final int MAX_LEVEL = 10_000;
private static final float[] LEVELS_PCT = new float[]{.25f, .66f, 1f};
//
final LayerDrawable progressBg = (LayerDrawable) progressTextView.getBackground();
for (int index = 0, count = LEVELS_PCT.length; index < count; index++) {
    progressBg.getDrawable(count - 1 - index)
            .setLevel((int) (MAX_LEVEL * LEVELS_PCT[index]));
}

enter image description here

Akaki Kapanadze
  • 2,552
  • 2
  • 11
  • 21
0

Try this method:

//Get the percentage ProgressBar and then apply the command to the text
float x = LoadingProgress.getProgress() ;
        

if (x > 0.2 && x < 0.6){
                MyTextView.setTextColor(getResources().getColor(R.color.colorGreen));
            }
            else if (x > 0.7)
            {
                MyTextView.setTextColor(getResources().getColor(R.color.colorYellow));
            } else {
                MyTextView.setTextColor(getResources().getColor(R.color.colorRed));
            }

Hope this solution helps you