Issue
Hi I want to make a Pie Progress bar in android like the attached image..
I have go through the following code but no gain.enter link description here
So i decided to write my own ProgressBarView. Here is my sample code ..
public class PieProgressView extends View {
private float mProgress;
private int MAX_ANGLE = 360;
public PieProgressView(Context context) {
super(context);
}
public PieProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PieProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawOval(canvas);
}
public void setProgress(int progress){
mProgress = (float) ((float)progress*3.6);
invalidate();
}
private void drawOval(Canvas canvas){
canvas.drawColor(Color.CYAN);
Paint paint = new Paint();
// smooths
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
RectF oval2 = new RectF(50, 50, 500, 500);
canvas.drawOval(oval2, paint);// opacity
Paint p = new Paint();
p.setColor(Color.BLACK);
canvas.drawArc(oval2, 270, mProgress, true, p);
System.out.println("drawOval Progress == "+mProgress);
//p.setAlpha(0x80); //
}
}
and the activity class from i call this..
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
pieProgressView = (PieProgressView)findViewById(R.id.pieprogress);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fillProgress();
}
});
}
private void fillProgress(){
for(int i=0;i<100 ; i++) {
pieProgressView.setProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Now during this for loop there is no progress shown but after completion of for loop it will shows the progress bar like in attached image showing a black progress.
can anyone tell me what the wrong with this code. Why this code not doing a continuous update ?
Solution
Thread.sleep( )
is causing the UI thread to block and hence you see the "filled" pie chart when the thread wakes up. I changed the code to use a CountDownTimer
instead and it works like a charm. Here's the code:
public class MainActivity extends AppCompatActivity {
PieProgressView pie;
CountDownTimer timer;
int progress = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pie = (PieProgressView) findViewById(R.id.pie);
scheduleNextTimer();
}
private CountDownTimer getTimer(){
return new CountDownTimer(1000,1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
Log.d("PROG",progress + "");
pie.setProgress( progress++ );
scheduleNextTimer();
}
};
}
private void scheduleNextTimer(){
if( progress < 100 ){
timer = getTimer();
timer.start();
}
}
}
Answered By - An SO User