android进度条与文本里面在中心呈现问题

时间:2018-03-27 18:00:34

标签: android progress-bar android-custom-view

我已经创建了一个自定义进度条,里面有文字。解决方案工作正常但现在文本被创建到进度条顶部而不是中心。 当活动暂停并恢复时。进度条再次渲染,然后文本出现在中心。 请参阅下面的代码。

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();
}
}

加载时的显示方式

enter image description here

重新创建后的显示方式

normal Image

2 个答案:

答案 0 :(得分:0)

在通货膨胀后尝试requestLayout()。它将measure()再次强制View。查看View的生命周期。

enter image description here

答案 1 :(得分:0)

也许有点晚,但是在获取文本边界之前先设置文本大小。

...
textPaint.setTextSize(getHeight() * 0.8f);
textPaint.getTextBounds(text, 0, text.length(), bounds);
...