I want to show a circular progress bar with countdown timer.And the timer starts from 10 mins to 0.In the Textview i am showing timer and that is working fine. But it is not reflecting in the progressbar.Progress bar is not at all changing. Below is the code which i have tried.
public class MainActivity extends AppCompatActivity {
ProgressBar barTimer;
CountDownTimer countDownTimer;
TextView textTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barTimer = findViewById(R.id.barTimer);
textTimer = findViewById(R.id.textTimer);
barTimer.setProgress(100);
startTimer(10);
}
private void startTimer(final int minuti) {
countDownTimer = new CountDownTimer(60 * minuti * 1000, 500) {
@Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
barTimer.setProgress((int)seconds);
textTimer.setText(String.format("%02d", seconds/60) + ":" + String.format("%02d", seconds%60));
}
@Override
public void onFinish() {
if(textTimer.getText().equals("00:00")){
textTimer.setText("STOP");
}
else{
textTimer.setText("2:00");
barTimer.setProgress(60*minuti);
}
}
}.start();
}
}
xml code
<TextView
android:id="@+id/textTimer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/barTimer"
android:layout_below="@+id/textTimer"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:progressDrawable="@drawable/circular_progress"
/>
Can anyone please tell me where it is wrong and how to solve this?
Your scaling factor is not correct and hence your maxProgess and setProgess values are also incorrect.There are two ways to fix this.
1.Set seconds = leftTimeInMilliseconds / 600 and not 1000.
Let's say X% = 1 second then 100% = 60 seconds,then X% = 100/60 seconds but we are calculating in milliseconds hence X% = 100/(60*1000) = 1/600 milliseconds. Also we have set 60 seconds for 100% hence multiply your setProgess and setMax by a factor 10.Since 600 seconds is 10 minutes.
barTimer.setProgress(1000);
barTimer.setMax(1000);
long seconds = leftTimeInMilliseconds / 600;
2.Similar to above rather than dividing by 600 divide 6000. seconds = leftTimeInMilliseconds / 6000;
Let's say X% = 1 second then 100% = 600 seconds(10 mins),then X% = 100/600 seconds but we are calculating in milliseconds hence X% = 100/(60*1000) = 1/6000 milliseconds.
Now since we are directly calculating for 10 mins no need to multiply your setProgess and setMax by any factor.
barTimer.setProgress(100);
barTimer.setMax(100);
long seconds = leftTimeInMilliseconds / 6000;
Also I would suggest setting countDownInterval to 1 sec rather 0.5 sec.
Hope this helps. Please mark the answer as accepted if it helps.