代码之家  ›  专栏  ›  技术社区  ›  Maurice Gaynor

随进度条移动的进度文本

  •  0
  • Maurice Gaynor  · 技术社区  · 8 年前

    我在Android中有一个水平进度条,可以按当前值设置动画。但是,我想对其进行更新,使其具有显示进度条进度的文本视图,并随着进度的增加沿着进度条的右边缘移动。我想也许我可以创建一个定制的ProgressBar并以某种方式利用onDraw方法,但我不确定之后的下一步是什么。有没有关于更好的方法或其他可以为我指明正确方向的建议?

    A basic example of what I'm trying to achieve

    非常感谢您的帮助。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Maurice Gaynor    8 年前

    我找到了一个解决我所要做的事情的方法!受我在上找到的代码启发 this post. 它将适用于ProgressBar的主要进度和次要进度。我首先扩展了ProgressBar类,并添加了所有构造函数方法。然后,我重写了onDraw方法,如下所示:

    @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);
    }
    
    推荐文章