问题
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 :
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?
回答1:
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
回答2:
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
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
回答3:
The easiest solution would be to use ProgressBar and a TextView on a Relative Layout. You provide your own style for both and that's it. There is no point in trying to do it on a TextView when ProgressBar has all what you need. Your layout would look like that:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<ProgressBar android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Doing something"
android:gravity="center"
android:layout_centerVertical="true"/>
</RelativeLayout>
You just need to play with widths and heights as you want them :)
来源:https://stackoverflow.com/questions/14977626/textview-as-a-progressbar-with-textcolor-minipulation