Custom ProgressBar widget

后端 未结 4 1086
挽巷
挽巷 2021-02-02 03:12

I am trying to do something similar to this but in Android.

\"alt

In Android I can extend the

4条回答
  •  时光取名叫无心
    2021-02-02 04:05

    You're already overriding onDraw, why not just draw the text strings yourself? Rather than go through the overhead of adding TextViews and messing with the padding, just use canvas.drawText to physically draw the text strings in the right place.

    You can specify the style and color of the text using a Paint object:

    Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(r.getColor(R.color.text_color));
    textPaint.setFakeBoldText(true);
    textPaint.setSubpixelText(true);
    textPaint.setTextAlign(Align.LEFT);
    

    And get the exact positioning by using the measureText method on that Paint object to find what width a particular string would be when drawn on a canvas:

    textWidth = (int)textPaint.measureText(mTexts[i]);
    

    Then you can iterate over your array of text strings and draw each string in the right place.

    @Override 
    protected void onDraw(Canvas canvas) {
      int myWidth = getMeasuredWidth()-LEFT_PADDING-RIGHT_PADDING;
      int separation = myWidth / (mSize-1);
    
      for (int i = 0; i++; i < mSize) {
        int textWidth = (int)textPaint.measureText(mTexts[i]);
        canvas.drawText(mTexts[i], 
                        LEFT_PADDING+(i*separation)-(int)(textWidth/2), 
                        TOP_PADDING, 
                        textPaint);
      }
    }
    

    You'll probably want to do the measurements in onMeasure instead of onDraw, and you should probably only measure the width of each string when you change the text or the paint, but I've put it all in one place to (hopefully) make it easier to follow.

提交回复
热议问题