Android Development Series (26): Use PopupWindow to create a dialog box style window
Creating a dialog box style window is simple and requires the following steps:
1. Call the PopupWindow constructor to create a PopupWindow object.
2. Call showAsDropDown (View v) of PopupWindow to display it as the drop-down component of the v component: or call the showAtLocation () method of PopupWindow to display the PopupWindow at the specified position.
First, create an Android project and edit the main. xml file:
We have defined a button to open the pop-up dialog box style window.
Then, edit the java code: PopupWindowTest. java on the main interface.
Import android. app. activity; import android. OS. bundle; import android. view. gravity; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. popupWindow; public class PopupWindowTest extends Activity {@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // load R. layout. bounds corresponding to popup View root = this. getLayoutInflater (). inflate (R. layout. popup, null); // create the PopupWindow object final PopupWindow popup = new PopupWindow (root, 280,360); Button button = (Button) findViewById (R. id. bn); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// The following PULL mode is displayed. // Popup. showAsDropDown (v); // PopupWindow is displayed at the specified position. showAtLocation (findViewById (R. id. bn), Gravity. CENTER, 20,20) ;}}); // obtain the close button in PopupWindow. Root. findViewById (R. id. close ). setOnClickListener (new View. onClickListener () {public void onClick (View v) {// close PopupWindowpopup. dismiss (); // responsible for destroying and hiding the key code of PopupWindow }});}}
We also wrote an xml file of the PopupWindow dialog box: popup. xml
Let's take a look at the effect: