【问题标题】:android progress bar with text inside in center render issue带有文本的android进度条在中心渲染问题
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    可能有点晚了,但在获取文本边界之前设置文本大小。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-26
      • 2014-04-02
      • 1970-01-01
      • 2010-09-22
      • 2019-08-08
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多