Android - set a ProgressBar to be a vertical bar instead of horizontal?

后端 未结 14 699
不知归路
不知归路 2020-11-30 22:22

I am trying to use a ProgressBar as a metering like display. I thought it was going to be an easy task and thought that ProgressBar had a property to set to be vertical, bu

14条回答
  •  星月不相逢
    2020-11-30 23:02

    I have the exact problem. Making a custom class (extending ProgressBar) will create code that are hard to maintain. Using a custom style will cause compatibility issue with different theme from new OS (e.g. lollipop)

    Eventually, I just apply a rotation animation to an horizontal progress bar. Inspired by Pete.

    1. Create the tag in your layout xml like normal horizontal progress bar.
    2. Make sure that the size and position of the ProgressBar is what you want after rotation. (Perhaps setting negative margin will help). In my code I rotate the view from 0,0.
    3. Use the method below to rotate and set new progress.

    Code:

    private void setProgress(final ProgressBar progressBar, int progress) {
        progressBar.setWillNotDraw(true);
        progressBar.setProgress(progress);
        progressBar.setWillNotDraw(false);
        progressBar.invalidate();
    }
    
    private void rotateView(final View v, float degree) {
        Animation an = new RotateAnimation(0.0f, degree);
        an.setDuration(0);
        an.setRepeatCount(0);
        an.setFillAfter(true);               // keep rotation after animation
        v.setAnimation(an);
    }
    

提交回复
热议问题