与ProgressBar一起移动的进度文本 [英] Progress text that moves along with ProgressBar

查看:135
本文介绍了与ProgressBar一起移动的进度文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android中有一个水平的ProgressBar,可以动画显示当前值.但是,我想对其进行更新,使其具有一个TextView,它显示进度条的进度,并随着进度的增加与进度条的右边缘一起移动.我想也许我可以创建一个自定义的ProgressBar并以某种方式利用onDraw方法,但是我不确定在那之后的下一步.对更好的方法有什么建议,或者可以为我指明正确方向的东西?

I have a horizontal ProgressBar in Android that animates to the current value. However, I would like to update it so that it has a TextView that shows the progress of the progress bar, and moves along with the right edge of the bar as the progress increases. I figure maybe I could create a custom ProgressBar and leverage the onDraw method somehow, but I'm not sure what the next move would be after that. Any suggestions on a better method or something that could point me in the right direction?

我要实现的目标的基本示例

非常感谢您的协助.

推荐答案

我找到了自己想做的解决方案!受到我在此帖子中找到的代码的启发. 它对于ProgressBar的主要进度和次要进度均适用.我首先要做的是扩展了ProgressBar类,并添加了所有构造函数方法.然后,我重写了onDraw方法,如下所示:

I found a solution for what I was trying to do! Inspired by the code I found on this post. It will work for both the primary and secondary progress of a ProgressBar. What I first did was extended the ProgressBar class, and added all the constructor methods. I then Overrided the onDraw method as seen below:

@Override
protected synchronized void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //Create the paint for the text
    Paint textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setColor(Color.WHITE);
    textPaint.setTextSize(getHeight()/4);
    Rect bounds = new Rect();
    textPaint.getTextBounds(textPrimary, 0, textPrimary.length(), bounds);

    //mTypeface is a typeface that I have being set in another function so
    //you don't have to use the default! :D
    if(mTypeface != null) {
        textPaint.setTypeface(mTypeface);
    }

    //I believe this is done to be able to put values in dp
    float density = getContext().getResources().getDisplayMetrics().density;

    //Point to draw text for primary progress
    float percentage = getProgress() / 100f; //get the total progress
    // distance the text should be from the end of the progress in dp
    // (paddingPrimary) is number of dp
    float x = getWidth() * percentage - (paddingPrimary * density);
    // center the text vertically
    float y = getHeight() / 2 - bounds.centerY();

    //Point to draw text for secondary progress
    float percentageSecondary = getSecondaryProgress() / 100f;
    float x2 = getWidth() * percentageSecondary - (paddingSecondary * density);
    float y2 = getHeight() / 2 - bounds.centerY();

    //Draw the numbers to the canvas
    //(textPrimary and textSecondary are the text to be drawn)
    canvas.drawText(textPrimary, x, y, textPaint);
    canvas.drawText(textSecondary, x2, y2, textPaint);
}

这篇关于与ProgressBar一起移动的进度文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆