In my app i have a custom progress bar
progress.xml
My solution is to use an Animated icon.
1°) Create an XML "animated" in Drawable :
2°) Put an imageview in your layout
3°) Put the following code in your activity :
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private ImageView micButton;
//-- for testing progress bar
private long fileSize = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-- declare animation
final AnimationDrawable[] rocketAnimation = new AnimationDrawable[1];
final ImageView micButton = findViewById(R.id.mic_button);
micButton.setBackgroundResource(R.drawable.micro_1);
//-- button listener
micButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//-- init button with animation
micButton.setBackgroundResource(R.drawable.mic_image);
rocketAnimation[0] = (AnimationDrawable) micButton.getBackground();
startprogress(rocketAnimation[0]);
}
});
}
public void startprogress(final AnimationDrawable rocketAnimation) {
rocketAnimation.start();
progressBar = new ProgressDialog(MainActivity.this);
//--reset filesize for demo
fileSize = 0;
//-- thread for demo
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
if(rocketAnimation.isRunning()){
rocketAnimation.stop();
}
}
}
}).start();
}
// file download simulator... a really simple
public int doSomeTasks() {
while (fileSize <= 1000000) { //1000000
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
} else if (fileSize == 400000) {
return 40;
} else if (fileSize == 500000) {
return 50;
} else if (fileSize == 600000) {
return 60;
}
}
return 100;
}
}