Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView as a progressbar with textcolor minipulation?

I'm working on improving my app's UI. And in the design I'm using I have a TextView that will act as a progress bar at certain time. The ruslt should look like this :

enter image description here

The thing is that parts of text will change their color while the progress is changing

I looked into spannablestring in android it would work if I can find the letters that are covered by the progress ( but I don't think this would be easy/accurate)

What I'm planning todo now is to use the following:

  • FrameLayout with :
  • background textView with a green text and white background.
  • front Linearlayout that changes width while progressing.
  • TextView with green background and white text that matches the framelayout width.

Is there a better approach?

like image 397
Mr.Me Avatar asked Feb 20 '13 10:02

Mr.Me


2 Answers

Much better approach would require you to override TextView class. You can use clipping, to split the TextView and draw two parts in different colors.

TextView tv = new TextView(this){
    @Override
    public void draw(Canvas canvas) {
        int color1 = Color.WHITE;
        int color2 = Color.GREEN;

        canvas.save();
        setTextColor(color1);
        setBackgroundColor(color2);
        canvas.clipRect(new Rect(0, 0, (int)(getWidth() * percent), getHeight()));
        super.draw(canvas);
        canvas.restore();

        canvas.save();
        setTextColor(color2);
        setBackgroundColor(color1);
        canvas.clipRect(new Rect((int)(getWidth() * percent), 0, getWidth(), getHeight()));
        super.draw(canvas);
        canvas.restore();
    }  
};

I hope you get the point

like image 97
Zielony Avatar answered Nov 15 '22 02:11

Zielony


I know this is an old question but I'm posting this because it might help someone else looking into similar situations hopefully it'll help someone going through this now. Here's an example

123

My solution basically is drawing in the canvas using drawText. The trick here is that you draw two texts, one inside the bar bounds and one inside the view bounds and using the following Z-index order (according to example used):

  • Text (white)
  • Red bar
  • Text (black)
  • view background

I've made an example on how to implement this, in this sample/lib I used a custom imageview to do it. Feel free to use it as anyway you like it: https://github.com/danilodanicomendes/InvertedTextProgressBar

like image 31
Danilo Avatar answered Nov 15 '22 04:11

Danilo