SoFunction
Updated on 2025-03-02

Detailed explanation of the prompt dialog box in Android (ProgressDialog, DatePickerDialog and TimePickerDialog & PopupWindow)

ProgressDialog (precision bar dialog):

1. Directly call the static method shown() provided by ProgressDialog to display

2. Create ProgressDialog, then set the parameters of the dialog box, and finally show() comes out

package .test3;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class MainActivity extends Activity implements {
  private Button btn_one;
  private Button btn_two;
  private Button btn_three;
  private ProgressDialog pd1 = null;
  private ProgressDialog pd2 = null;
  private final static int MAXVALUE = 100;
  private int progressStart = 0;
  private int add = 0;
  private Context mContext = null;
  //Define a Handler for updating progress. Since the interface can only be updated by the main thread, the Handler must be passed on information.  final Handler hand = new Handler()
  {
    @Override
    public void handleMessage(Message msg) {
      //If the information code is received here, it is 123      if( == 123)
      {
        //Set the current value of the progress bar        (progressStart);
      }
      //If the current value is greater than or equal to the maximum value of the progress bar, call the dismiss() method to close the dialog box      if(progressStart >= MAXVALUE)
      {
        ();
      }
    }
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    mContext = ;
    bindViews();
  }
  private void bindViews() {
    btn_one = (Button) findViewById(.btn1);
    btn_two = (Button) findViewById(.btn2);
    btn_three = (Button) findViewById(.btn3);
    btn_one.setOnClickListener(this);
    btn_two.setOnClickListener(this);
    btn_three.setOnClickListener(this);
  }
  @Override
  public void onClick(View v) {
    switch (()){
      case .btn1:
        //The parameters here are, context, title, content, whether the progress is displayed, and whether the cancel button can be closed        (, "Resource loading", "Resource is loading, please wait...",false,true);
        break;
      case .btn2:
        pd1 = new ProgressDialog(mContext);
        //Set the title, content, whether to close with the Cancel button, whether to display progress        ("Software Update");
        ("The software is being updated, please wait...");
        (true);
        //This is the style of setting the progress bar. HORIZONTAL is the horizontal progress bar and SPINNER is the circular progress bar.        (ProgressDialog.STYLE_HORIZONTAL);
        (true);
        //Call the show() method to display the ProgressDialog        ();
        break;
      case .btn3:
        //Initialize attributes        progressStart = 0;
        add = 0;
        //Set some properties in turn        pd2 = new ProgressDialog();
        (MAXVALUE);
        ("File reading");
        ("The file is loading, please wait...");
        //This is set to not be closed by pressing the Cancel button        (false);
        (ProgressDialog.STYLE_HORIZONTAL);
        //The setting here is whether to display progress, and set to false to display it!        (false);
        ();
        //Create a new thread here and override the run() method.        new Thread()
        {
          public void run()
          {
            while(progressStart < MAXVALUE)
            {
              //The algorithm here determines the change of the progress bar, and can be written as needed              progressStart = 2 * usetime() ;
              //Send the information code to handle for update interface              (123);
            }
          }
        }.start();
        break;
    }
  }
  // Set a time-consuming method here:  private int usetime() {
    add++;
    try{
      (100);
    }catch (InterruptedException e) {
      ();
    }
    return add;
  }
}

/TimePickerDialog is only for users to choose date and time, and has no effect on the system time of the Android system, date

The construction methods of the two of them are very similar: DatePickerDialog (context; () listener; year; month; day)
TimePickerDialog (context; () listener; hours, minutes, whether to use a 24-hour system)

public class MainActivity extends AppCompatActivity implements {
  private Button btn_date;
  private Button btn_time;
  private String result = "";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    bindViews();
  }
  private void bindViews() {
    btn_date = (Button) findViewById(.btn_date);
    btn_time = (Button) findViewById(.btn_time);
    btn_date.setOnClickListener(this);
    btn_time.setOnClickListener(this);
  }
  @Override
  public void onClick(View v) {
    result = "";
    switch (()){
      case .btn_date:
        Calendar cale1 = ();
        new DatePickerDialog(,new () {
          @Override
          public void onDateSet(DatePicker view, int year, int monthOfYear,
                     int dayOfMonth) {
            //The month you get here needs to add 1~            result += "You chose"+year+"Year"+(monthOfYear+1)+"moon"+dayOfMonth+"day";
            (getApplicationContext(), result, Toast.LENGTH_SHORT).show();
          }
        }
            ,()
            ,()
            ,(Calendar.DAY_OF_MONTH)).show();
        break;
      case .btn_time:
        Calendar cale2 = ();
        new TimePickerDialog(, new () {
          @Override
          public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            result = "";
            result += "The time you chose is:"+hourOfDay+"hour"+minute+"point";
            (getApplicationContext(), result, Toast.LENGTH_SHORT).show();
          }
        }, (Calendar.HOUR_OF_DAY), (), true).show();
        break;
    }
  }
}

The last UI control used to display information - PopupWindow (floating box). If you want to know what it looks like, you can open the QQ of your phone and press an item in the list. At this time, a small black dialog box pops up. This is PopupWindow. Unlike the AlertDialog dialog box, its position can be random; in addition, AlertDialog is not blocking threads, while PopupWindow is blocking threads

1) Several commonly used construction methods

We can see in the document that there are as many as nine constructor methods provided to us. Here are only a few constructor methods that are used more frequently in development:

public PopupWindow (Context context)
public PopupWindow(View contentView, int width, int height)
public PopupWindow(View contentView)
public PopupWindow(View contentView, int width, int height, boolean focusable)

There is no need to explain the parameters. The contentView is the View displayed by PopupWindow. Whether focusable displays the focus

2) Some commonly used methods

Here are a few more commonly used methods, and you can check the documents for others:

setContentView(View contentView): Set the View displayed by PopupWindow
getContentView(): Get the View displayed by PopupWindow
showAsDropDown(View anchor): relative to the position of a control (right lower left), without offset
showAsDropDown(View anchor, int xoff, int yoff): There is an offset relative to the position of a certain control
showAtLocation(View parent, int gravity, int x, int y): relative to the position of the parent control (such as center, bottom, etc.), you can set offset or no offset. PS:parent parameter is as long as it is the view in the activity!
setWidth/setHeight: Set the width and height, you can also specify the width and height in the construction method. In addition to writing specific values, you can also use WRAP_CONTENT or MATCH_PARENT. The width and height attributes of popupWindow directly correspond to the first layer View.

setFocusable(true): Set the focus. After PopupWindow pops up, all touch screen and physical keys are processed by PopupWindow. The response to any other event must occur after the disappearance of PopupWindow (except events at the system level such as home). For example, when a PopupWindow appears, pressing the back key first makes PopupWindow disappear, and the second press is to exit the activity. To be precise, if you want to exit the activity, you have to first make PopupWindow disappear, because it is not the case that the back PopupWindow will disappear under any circumstances. You must set the background of PopupWindow.

setAnimationStyle(int): Set animation effect

public class MainActivity extends Activity {
  private Button btn_show;
  private Context mContext;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    mContext = ;
    btn_show = (Button) findViewById(.btn_show);
    btn_show.setOnClickListener(new () {
      @Override
      public void onClick(View v) {
        initPopWindow(v);
      }
    });
  }
  private void initPopWindow(View v) {
    View view = (mContext).inflate(.item_popup, null, false);
    Button btn_xixi = (Button) (.btn_xixi);
    Button btn_hehe = (Button) (.btn_hehe);
    //1. Construct a PopupWindow, the parameters are the loaded View, width and height    final PopupWindow popWindow = new PopupWindow(view,
        .WRAP_CONTENT, .WRAP_CONTENT, true);
    (.anim_pop); //Set loading animation    //In order to click on non-PopupWindow areas, PopupWindow will disappear if there is no below    //For code, you will find that when you display PopupWindow, no matter how many times you press the back key    //PopupWindow will not be closed, and the program cannot be exited. Adding the following code can solve this problem    (true);
    (new () {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        return false;
        // If true is returned here, the touch event will be intercepted        // After intercepting, the onTouchEvent of PopupWindow is not called, so clicking on the external area cannot dismiss      }
    });
    (new ColorDrawable(0x00000000));  //To set a background for popWindow to be effective    //Set the position of popupWindow display, the parameters are the reference View, the offset of the x-axis, and the offset of the y-axis, respectively.    (v, 50, 0);
    //Set the event of the button in popupWindow    btn_xixi.setOnClickListener(new () {
      @Override
      public void onClick(View v) {
        (, "You clicked hehe~", Toast.LENGTH_SHORT).show();
      }
    });
    btn_hehe.setOnClickListener(new () {
      @Override
      public void onClick(View v) {
        (, "You clicked haha~", Toast.LENGTH_SHORT).show();
        ();
      }
    });
  }
}