Android点击button弹出ProgressDialog,响应结束后ProgressDialog消失
程序员文章站
2022-06-16 09:43:24
ProgressDialog与Handler结合使用,事件响应前弹出dialog,事件响应结束后dialog自动消失。...
使用背景:项目中需要使用几个机器学习模型,由于加载很缓慢,所以考虑用ProgressDialog来进行提示,预测结束后dialog自动消失。
效果如下:
1.声明Handler和ProgressDialog
public ProgressDialog progressDialog;
public Handler handler = null;
2.点击事件
query.setOnClickListener(v -> {
progressDialog = new ProgressDialog(AdaBoostActivity.this);
progressDialog.setTitle("提示");
progressDialog.setMessage("正在加载...");
progressDialog.setIcon(R.drawable.running);
new Thread(){
public void run(){
try{
runOnUiThread(() -> createList());
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
}.start();//线程启动
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
ToastUtil.showMessage(AdaBoostActivity.this, "预测完成!");
}
};
progressDialog.show();
});
其中:
runOnUiThread(() -> createList());
createList()方法完成后ProgressDialog消失,因为createList()中涉及到渲染TextView,所以使用runOnUiThread()。
createList完成后handler发送消息:
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
然后销毁dialog:
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
ToastUtil.showMessage(AdaBoostActivity.this, "预测完成!");
}
};
3.销毁线程
@Override
protected void onDestroy() {
super.onDestroy();
if(handler != null) {
handler.removeCallbacksAndMessages(null);
}
}
本文地址:https://blog.csdn.net/Cyril_KI/article/details/114268611