Подтвердить что ты не робот

Как показать диалог прогресса в Android?

Я хочу показать ProgressDialog когда нажимаю на кнопку "Войти", и для перехода на другую страницу требуется время. Как я могу это сделать?

4b9b3361

Ответ 1

Ты лучше попробуй с AsyncTask

Образец кода -

private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog dialog;

    public YourAsyncTask(MyMainActivity activity) {
        dialog = new ProgressDialog(activity);
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Doing something, please wait.");
        dialog.show();
    }

    protected Void doInBackground(Void... args) {
        // do background work here
        return null;
    }

    protected void onPostExecute(Void result) {
         // do UI work here
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}

Используйте приведенный выше код в вашей активности кнопки входа в систему. И делать вещи в doInBackground и onPostExecute

Обновить:

ProgressDialog интегрирован с AsyncTask как вы сказали, что ваша задача требует времени для обработки.

Обновить:

Класс ProgressDialog устарел с API 26

Ответ 2

ProgressDialog pd = new ProgressDialog(yourActivity.this);
pd.setMessage("loading");
pd.show();

И все, что вам нужно.

Ответ 3

Точка, которую вы должны запомнить, когда речь заходит о Диалогом прогресса, является то, что вы должны запускать ее в отдельном потоке. Если вы запустите его в своем потоке пользовательского интерфейса, вы не увидите диалога.

Если вы новичок в Android Threading, вы должны узнать о AsyncTask. Это поможет вам реализовать безболезненные темы.

пример кода

private class CheckTypesTask extends AsyncTask<Void, Void, Void>{
        ProgressDialog asyncDialog = new ProgressDialog(IncidentFormActivity.this);
        String typeStatus;


        @Override
        protected void onPreExecute() {
            //set message of the dialog
            asyncDialog.setMessage(getString(R.string.loadingtype));
            //show dialog
            asyncDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            //don't touch dialog here it'll break the application
            //do some lengthy stuff like calling login webservice

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //hide the dialog
            asyncDialog.dismiss();

            super.onPostExecute(result);
        }

}

Удачи.

Ответ 4

Для использования ProgressDialog используйте код ниже

ProgressDialog progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please Wait....");

Для запуска ProgressDialog используйте

progressdialog.show();

progressdialog.setCancelable(false); используется таким образом, что ProgressDialog не может быть отменен, пока работа не будет завершена.

Чтобы остановить ProgressDialog используйте этот код (когда ваша работа закончена):

progressdialog.dismiss();'

Ответ 5

Простое кодирование в вашей activity как показано ниже:

private ProgressDialog dialog = new ProgressDialog(YourActivity.this);    
dialog.setMessage("please wait...");
dialog.show();
dialog.dismiss();

Ответ 6

Это хороший способ использования диалога

private class YourAsyncTask extends AsyncTask<Void, Void, Void> {

   ProgressDialog dialog = new ProgressDialog(IncidentFormActivity.this);

   @Override
    protected void onPreExecute() {
        //set message of the dialog
        dialog.setMessage("Loading...");
        //show dialog
        dialog.show();
        super.onPreExecute();
    }

   protected Void doInBackground(Void... args) {
    // do background work here
    return null;
   }

   protected void onPostExecute(Void result) {
     // do UI work here
     if(dialog != null && dialog.isShowing()){
       dialog.dismiss()
     }

  }
}

Ответ 7

Объявите ваш диалог прогресса:

ProgressDialog progressDialog;  

Чтобы начать диалог прогресса:

progressDialog = ProgressDialog.show(this, "","Please Wait...", true);  

Чтобы закрыть диалог прогресса:

 progressDialog.dismiss();

Ответ 8

когда вы вызываете oncreate()

new LoginAsyncTask ().execute();

Здесь как использовать в потоке.

ProgressDialog progressDialog;

  private class LoginAsyncTask extends AsyncTask<Void, Void, Void> {
  @Override
    protected void onPreExecute() {
        progressDialog= new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Please wait...");
        progressDialog.show();
        super.onPreExecute();
    }

     protected Void doInBackground(Void... args) {
        // Parsse response data
        return null;
     }

     protected void onPostExecute(Void result) {
        if (progressDialog.isShowing())
                        progressDialog.dismiss();
        //move activity
        super.onPostExecute(result);
     }
 }

Ответ 9

ProgressDialog dialog = 
   ProgressDialog.show(yourActivity.this, "", "Please Wait...");

Ответ 10

ProgressDialog pd = new ProgressDialog(yourActivity.this);
pd.show();

Ответ 11

  final ProgressDialog loadingDialog = ProgressDialog.show(context,
     "Fetching BloodBank List","Please wait...",false,false);  // for  showing the 
    // dialog  where context is the current context, next field is title followed by
    // message to be shown to the user and in the end intermediate field
    loadingDialog.dismiss();// for dismissing the dialog 

для получения дополнительной информации Android - В чем разница между progressDialog.show() и ProgressDialog.show()?

Ответ 12

ProgressDialog теперь официально устарел в Android O. Я использую DelayedProgressDialog от https://github.com/Q115/DelayedProgressDialog, чтобы выполнить задание.

Использование:

DelayedProgressDialog progressDialog = new DelayedProgressDialog();
progressDialog.show(getSupportFragmentManager(), "tag");

Ответ 13

ProgressDialog устарел, поскольку API 26

Тем не менее вы можете использовать это:

public void button_click(View view)
{
    final ProgressDialog progressDialog = ProgressDialog.show(Login.this,"Please Wait","Processing...",true);
}

Ответ 14

Простой способ:

ProgressDialog pDialog = new ProgressDialog(MainActivity.this); //Your Activity.this
pDialog.setMessage("Loading...!");
pDialog.setCancelable(false);
pDialog.show();

Ответ 15

        final ProgressDialog progDailog = ProgressDialog.show(Inishlog.this, contentTitle, "even geduld aub....", true);//please wait....

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Barcode_edit.setText("");
                showAlert("Product detail saved.");


            }

        };

        new Thread() {
            public void run() {
                try {
         } catch (Exception e) {

                }
                handler.sendEmptyMessage(0);
                progDailog.dismiss();
            }
        }.start();

Ответ 16

Шаг 1: Creata XML файл

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <Button
        android:id="@+id/btnProgress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Progress Dialog"/>
</LinearLayout>

Шаг 2: Создайте SampleActivity.java

package com.scancode.acutesoft.telephonymanagerapp;


import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SampleActivity extends Activity implements View.OnClickListener {
    Button btnProgress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnProgress = (Button) findViewById(R.id.btnProgress);
        btnProgress.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        final ProgressDialog progressDialog = new ProgressDialog(SampleActivity.this);
        progressDialog.setMessage("Please wait data is Processing");
        progressDialog.show();

//        After 2 Seconds i dismiss progress Dialog

        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2000);
                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}