我该如何在Android应用程序中以编程方式显示沙漏呢?
你可以使用一个ProgressDialog
:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Thinking...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
以上代码将在您的Activity
上方显示以下对话框:
或者(并且)您可以在Activity
的标题栏中显示进度指示器。
您需要在Activity
的onCreate()
方法顶部使用以下代码请求此功能:need to request this as a feature
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
然后像这样打开它:
setProgressBarIndeterminateVisibility(true);
并像这样将其关闭:
setProgressBarIndeterminateVisibility(false);
以下是使用AsyncTask的简单示例:
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
...
new MyLoadTask(this).execute(); //If you have parameters you can pass them inside execute method
}
private class MyLoadTask extends AsyncTask <Object,Void,String>{
private ProgressDialog dialog;
public MyLoadTask(MyActivity act) {
dialog = new ProgressDialog(act);
}
protected void onPreExecute() {
dialog.setMessage("Loading...");
dialog.show();
}
@Override
protected String doInBackground(Object... params) {
//Perform your task here....
//Return value ... you can return any Object, I used String in this case
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return(new String("test"));
}
@Override
protected void onPostExecute(String str) {
//Update your UI here.... Get value from doInBackground ....
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
AsyncTask
。你可以在onPreExecute()
和onPostExecute()
中显示和隐藏ProgressDialog
,并在doInBackground
中完成你的工作。http://android-developers.blogspot.com/2009/05/painless-threading.html - David Webb