[英]Display loading dialog while running method in Android?
I have a method setup that takes about 3-5 seconds to run (because it does something online) and I would like to show a loading dialog, but I cant figure out how to do it, I tried starting the loading dialod before I called the method then tried to dismiss it right after like this: 我有一个方法设置,运行大约需要3-5秒(因为它在网上做了一些事情),我想显示一个加载对话框,但我无法弄清楚如何做到这一点,我试着在我打电话之前启动加载dialod然后该方法试图在这之后立即解雇它:
dialog.show();
myMethod();
dialog.cancel();
But that didn't work, does anyone have any suggestions? 但这没用,有没有人有任何建议?
AsyncTask is my Favouite but you may use Handlers too :) AsyncTask是我的Favouite但你也可以使用Handlers :)
Invest your time to go through this nice blog . 花时间去浏览这个不错的博客 。
Below snippet will help you. 以下代码段将为您提供帮助。
package org.sample;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
public class Hello extends Activity {
private Handler handler;
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dialog = new ProgressDialog(this);
dialog.setMessage("Please Wait!!");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.show();
new Thread() {
public void run() {
// Do operation here.
// ...
// ...
// and then mark handler to notify to main thread
// to remove progressbar
//
// handler.sendEmptyMessage(0);
//
// Or if you want to access UI elements here then
//
// runOnUiThread(new Runnable() {
//
// public void run() {
// Now here you can interact
// with ui elemements.
//
// }
// });
}
}.start();
handler = new Handler() {
public void handleMessage(android.os.Message msg) {
dialog.dismiss();
};
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.