22

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

4

2 回答 2

45

您可以使用ProgressDialog

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

上面的代码将在您的顶部显示以下对话框Activity

替代文字

或者(或另外)您可以在Activity.

替代文字

需要使用以下代码onCreate()在您的方法顶部附近请求此功能:Activity

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

然后像这样打开它:

setProgressBarIndeterminateVisibility(true);

并像这样关闭它:

setProgressBarIndeterminateVisibility(false);
于 2010-01-26T15:11:52.920 回答
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();
            }           
        }
    }
于 2014-12-04T16:44:31.777 回答