【发布时间】:2018-03-27 18:00:33
【问题描述】:
我创建了一个自定义进度条,其中包含文本。解决方案工作正常,但现在文本被创建到进度条的顶部而不是中心。 当 Activity 暂停和恢复时。进度条再次呈现,然后文本出现在中心。 请在下面查看我的代码。
public class TextProgressBar extends ProgressBar {
private String text;
private Paint textPaint;
public TextProgressBar(Context context) {
super(context);
text = "";
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
//textPaint.setShadowLayer(1,1,1,Color.WHITE);
textPaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
}
public TextProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
text = "";
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
}
public TextProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
text = "";
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
}
@Override
protected synchronized void onDraw(Canvas canvas) {
// First draw the regular progress bar, then custom draw our text
super.onDraw(canvas);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
textPaint.setTextSize(getHeight() * 0.8f);
int x = (getWidth()/2) - bounds.centerX();
int y = (getHeight()/2) - bounds.centerY();
canvas.drawText(text, x, y, textPaint);
}
public synchronized void setText(String text) {
this.text = text;
drawableStateChanged();
}
public synchronized void setPercentText(int percentText){
this.text = percentText + " %";
}
public void setTextColor(int color) {
textPaint.setColor(color);
drawableStateChanged();
}
}
加载时的样子
重新创建后的样子
【问题讨论】:
-
尝试在通货膨胀后立即在
progressBar上调用requestLayout()。 -
像魅力一样工作..谢谢..请将其发布为答案,以便我将其标记为正确。
标签: android progress-bar android-custom-view