安卓沙漏

22

我该如何在Android应用程序中以编程方式显示沙漏呢?

2个回答

45

你可以使用一个ProgressDialog

ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Thinking...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();

以上代码将在您的Activity上方显示以下对话框:

alt text

或者(并且)您可以在Activity的标题栏中显示进度指示器。

alt text

您需要在ActivityonCreate()方法顶部使用以下代码请求此功能:need to request this as a feature

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

然后像这样打开它:

setProgressBarIndeterminateVisibility(true);

并像这样将其关闭:

setProgressBarIndeterminateVisibility(false);

问题在于显示对话框后,我运行了一个相对较长的处理过程,这阻止了当我不再需要时出现的处理结束时的对话框的显示! - Arutha
1
看一下AsyncTask。你可以在onPreExecute()onPostExecute()中显示和隐藏ProgressDialog,并在doInBackground中完成你的工作。http://android-developers.blogspot.com/2009/05/painless-threading.html - David Webb
也许值得阅读Android开发者指南中的“响应式设计”一章。http://developer.android.com/guide/practices/design/responsiveness.html - Jeremy Logan
ProgressDialog() 构造函数未定义。如何解决或替换 "this"? - neobie
@neobie 将“this”设置为您想要显示进度对话框的上下文。 - Ushal Naidoo
所有超过2年的Android帖子应该被清除。 - Atys

3

以下是使用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();
            }           
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接