Custom ProgressBar widget

后端 未结 4 1080
挽巷
挽巷 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 03:56

    You can use this... not exact what you looking for... but really easy to set up and customize...

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-02 04:11

    Just a try. You could put your custom progressBar inside a FrameLayout then, inside this layout, you have to add three TextViews with fill_parent as width. Then you can align the three texts in this way: left, center and right. Your texts shouldn't overwrite and you can adjust a little their position using margins.

    0 讨论(0)
  • 2021-02-02 04:15

    You can set the TextViews to have:

    android:layout_width="0dp"
    android:layout_weight="1"
    

    This will let the android framework take care of the placing of the TextViews and save you from manually calculating the padding of each one.

    0 讨论(0)
提交回复
热议问题