Android_Slip_1B

Step1:

Open Android Studio and create a new project with an Empty Activity template.

In the res/layout/activity_main.xml file, add a Button widget:

    <Button
    android:id="@+id/buttonShowProgressDialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show ProgressDialog"
    android:onClick="showProgressDialog"/>


In the MainActivity.java file, implement the showProgressDialog method and create an AsyncTask to simulate a background task:

    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    }

    public void showProgressDialog(View view) {
    new BackgroundTask().execute();
    }

    private class BackgroundTask extends AsyncTask {
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(MainActivity.this);
    progressDialog.setMessage("Loading...");
    progressDialog.setCancelable(false);
    progressDialog.show();
    }

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

    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return null;
    }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if (progressDialog.isShowing()) {
    progressDialog.dismiss();
    }
    }
    }
    }

Step2:

Run the application, and when you click the "Show ProgressDialog" button, a ProgressDialog will appear, simulating a background task. After a simulated delay, the ProgressDialog will be dismissed.

No comments:

Post a Comment