Loading dialog in android studio java for all API level - No Deprecation

Loader in Android studio using AlertDialog with custom layout



Loading dialog  in android studio java for all API level - No Deprecation using AlertDialog

Here is the example, Create a class level variable for dialog of type AlertDialog. 

AlertDialog dialog;


Create one method setProgressDialog() where we initialise the variable and set the custom xml 

public void setProgressDialog() {

  int llPadding = 30;
  LinearLayout ll = new LinearLayout(this);
  ll.setOrientation(LinearLayout.HORIZONTAL);
  //ll.setPadding(20,30,33,33);
  ll.setPadding(llPadding, llPadding, llPadding, llPadding);
  ll.setGravity(Gravity.LEFT);
  LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT);
  llParam.gravity = Gravity.CENTER;
  ll.setLayoutParams(llParam);

  ProgressBar progressBar = new ProgressBar(this);
  progressBar.setIndeterminate(true);
  progressBar.setPadding(0, 0, llPadding, 0);
  progressBar.setLayoutParams(llParam);

  llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT);
  llParam.gravity = Gravity.CENTER;
  TextView tvText = new TextView(this);
  tvText.setText("Loading ...");
  tvText.setTextColor(Color.parseColor("#000000"));
  tvText.setTextSize(20);
  tvText.setLayoutParams(llParam);

  ll.addView(progressBar);
  ll.addView(tvText);

  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setCancelable(false);
  builder.setView(ll);

  dialog = builder.create();
  dialog.show();
  Window window = dialog.getWindow();
  if (window != null) {
    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
    layoutParams.copyFrom(dialog.getWindow().getAttributes());
    layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
    layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
    dialog.getWindow().setAttributes(layoutParams);
  }
}


here, there is a code to show or hide a loader dialog

//to show loader
setProgressDialog();
//to hide loader
dialog.dismiss();

Hopefully 🤞 this will help

Post a Comment

0 Comments