Reputation: 1590
So I'm trying to create a progress bar for achievements in my application. These progress bars should show their progresses once the activity opens. I'm familiar with regular progress bars in which you update your list status and setprogress on the progress bar, but somehow I couldn't manage to complete this task. In below code, I tried to create a progress bar that fills up to 30/100 and then stops, as if the "achievement progress" was 30. For the ease of understanding, I'm working with simple integers. Current behaviour is not even close, as the progress bar is just spinning without any progress update. Note that the progress is not related to any other component other than simple integers.
Edit: This is the behaviour I want: https://dribbble.com/shots/2758323-Ring-Progress
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_points);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setIndeterminate(false);
new TimedProgress();
}
class TimedProgress {
Timer timer;
public TimedProgress() {
timer = new Timer();
timer.schedule(new ProgressTask(), 0, 500);
}
class ProgressTask extends TimerTask {
int progress = 0;
public void run() {
if (progress <30) {
updateProgress(progress);
progress++;
} else {
timer.cancel();
}
}
}
}
public void updateProgress(final int progress) {
if (null != progressBar) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress((int) progress);
}
}
Layout:
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"/>
Upvotes: 1
Views: 617
Reputation: 522
Use a timer to count the progress steps, e.g. every 1/2 second (500 ms). Here is a basic java timer that you can have fun converting into an AsyncTask for Android! Execute the AsyncTask, and every 1/2 second the timer will update the progress bar.
class TimedProgress {
Timer timer;
public TimedProgress() {
timer = new Timer();
timer.schedule(new ProgressTask(), 0, 500);
}
class ProgressTask extends TimerTask {
int progress = 0;
public void run() {
if (progress <30) {
updateProgress(progress);
progress++;
} else {
timer.cancel();
}
}
}
}
public void updateProgress(final int progress) {
if (null != progressBar) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress((int) progress);
}
}
Upvotes: 1