Android Imitation QQ message prompts to implement pop-up dialog box _android

Source: Internet
Author: User

This article in the "7 Forms of Android dialog use examples" in this article on the basis of learning, specific content as follows

1. Overview

Android native controls have always been known to be ugly (the new material design says otherwise), so almost every application will customize its own UI style. And the pop-up prompt box customization is particularly common, this article we will imitate the QQ exit prompt box to look at the common several custom prompt box implementation way.
Several of the pop-up implementation methods used here are summarized as follows:

Custom Dialog
Custom Popupwindow
Custom Layout View
Dialog style of activity
Fragmentdialog

First look at the final effect of the picture:

2. Practice

As mentioned above, several implementations can achieve the same demo effect, but they are different. Here first list each kind of concrete realization, finally summarizes and concludes.
Before that, first look at the implementation of the dialog box shared layout layout/confirm_dialog.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=" wrap_content "android:layout_marginleft=" 5DP " android:layout_marginright= "5DP" android:background= "@drawable/confirm_dialog_bg" android:orientation= "vertical" > <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" @android: Color/transparent "android:orientation=" vertical "> <textview android:id=" @+id/title_name "Andro Id:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:gravity= "Center_horizontal" Android:pa Ddingbottom= "10DP" android:paddingtop= "15DP" android:text= "message Title" android:textcolor= "@android: Color/blac K "android:textsize=" 20sp "android:visibility=" visible "/> </LinearLayout> <linearlayout Android:la Yout_width= "Fill_parent" Android:layout_height= "Fill_parent" android:background= "@android: Color/transparent" android:orientation= "vertical" > <textview Android:id= "@+id/text_view" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android: layout_marginleft= "15DP" android:layout_marginright= "15DP" android:layout_margintop= "10DP" android:textcolor= "@an Droid:color/black "android:text=" "This is message content" android:textsize= "16dip"/> <view android:layou T_width= "Match_parent" android:layout_height= "1px" android:layout_margintop= "15dip" android:background= "#c5c5c5" /> <linearlayout android:layout_width= "fill_parent" android:layout_height= "50dip" android:background= "@a  Ndroid:color/transparent "android:gravity=" center_horizontal "android:orientation=" Horizontal "> <!--Cancel button --> <button android:id= "@+id/btn_cancel android:layout_width=" wrap_content "android:layout_height=" Match_parent "Android: layout_weight= "1" android:text= "Cancel" android:textstyle= "bold" android:textcolor= "#0072c6" Android:back 
    ground= "@drawable/confirm_dialog_cancel_selector" android:textsize= "15sp"/> <!--confirmation button--> <view
    Android:layout_width= "1px" android:layout_height= "match_parent" android:layout_gravity= "Center_horizontal"
    android:background= "#c5c5c5"/> <button android:id= "@+id/btn_ok" android:layout_width= "Wrap_content"
    android:layout_height= "Match_parent" android:layout_weight= "1" android:text= "OK" android:textstyle= "bold" Android:textcolor= "#0072c6" android:background= "@drawable/confirm_dialog_ok_selector" android:textsize= "15SP"/&G
  T

 </LinearLayout> </LinearLayout> </LinearLayout>

You can see the effect just through the layout preview:

Below we use this layout to display the message balloon in the above ways.

2.1 Dialog

This is the most basic and most common non-blocking dialog box. Concrete form can be divided into seven kinds, detailed see various articles on the Internet, casually cite a 7 forms of Android dialog use examples.
(Note: The official after the launch of the Fragmentdialog is not recommended directly use dialog to create a dialog box, this is something)

Our Custom prompt box Confirmdialog inherits from Dialog, uses Confirm_dialog.xml to initialize the layout, and binds the corresponding events.

public class Confirmdialog extends Dialog {private context context;
 Private TextView Titletv,contenttv;
 Private View okbtn,cancelbtn;

 Private Ondialogclicklistener Dialogclicklistener;
  Public Confirmdialog {Super (context);
  This.context = context;
 Initalize ();
  }//Initialize view private void Initalize () {Layoutinflater Inflater = layoutinflater.from (context);
  View view = Inflater.inflate (R.layout.confirm_dialog, NULL);
  Setcontentview (view);

  Initwindow ();
  Titletv = (TextView) Findviewbyid (r.id.title_name);
  Contenttv = (TextView) Findviewbyid (R.id.text_view);
  OKBTN = Findviewbyid (R.ID.BTN_OK);
  CANCELBTN = Findviewbyid (R.id.btn_cancel);
    Okbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {dismiss ();
    if (Dialogclicklistener!= null) {Dialogclicklistener.onokclick ();
  }
   }
  }); Cancelbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (ViewV) {dismiss ();
    if (Dialogclicklistener!= null) {Dialogclicklistener.oncancelclick ();
 }
   }
  });
  /** * Add black translucent background/private void Initwindow () {Window Dialogwindow = GetWindow (); Dialogwindow.setbackgrounddrawable (new colordrawable (0));//Set window background Dialogwindow.setsoftinputmode ( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)//Set Input Method display mode Windowmanager.layoutparams LP =
  Dialogwindow.getattributes (); Displaymetrics d = context.getresources (). Getdisplaymetrics (),//get screen size lp.width = (int) (D.widthpixels * 0.8);  Width for screen 80% lp.gravity = Gravity.center;
 Center Center Dialogwindow.setattributes (LP);
 public void Setondialogclicklistener (Ondialogclicklistener clicklistener) {dialogclicklistener = ClickListener;
  /** * Add button click event * * public interface ondialogclicklistener{void Onokclick ();
 void Oncancelclick ();

 }
}

2.2 Popupwindow

Popupwindow is a blocking dialog box, and the program will only continue to run when the operation is exited. In addition Popupwindow can determine its own position according to freedom. There are two kinds of offset and no offset according to the position, which can be divided into relative to a control (anchor anchor) and relative to the parent control according to the different reference point. Specifically as follows

Showasdropdown (View anchor): relative to the position of a control (directly to the lower left), no offset
Showasdropdown (View anchor, int xoff, int yoff): relative to the position of a control (directly below), has an offset
Showatlocation (View parent, int gravity, int x, int y): You can set an offset or no offset relative to the parent control's position (such as a positive central gravity.center, lower Gravity.bottom, and so on)

Here just to achieve the same display effect, only to demonstrate the use of Showatbottom:

public class Confirmpopwindow extends popupwindow{the private context;
 Private TextView Titletv,contenttv;
 Private View okbtn,cancelbtn;

 Private Ondialogclicklistener Dialogclicklistener;
  Public Confirmpopwindow {Super (context);
  This.context = context;
 Initalize ();
  private void Initalize () {Layoutinflater Inflater = layoutinflater.from (context);
  View view = Inflater.inflate (R.layout.confirm_dialog, NULL);
  Setcontentview (view);

  Initwindow ();
  Titletv = (TextView) View.findviewbyid (r.id.title_name);
  Contenttv = (TextView) View.findviewbyid (R.id.text_view);
  OKBTN = View.findviewbyid (R.ID.BTN_OK);
  CANCELBTN = View.findviewbyid (R.id.btn_cancel);
    Okbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {dismiss ();
    if (Dialogclicklistener!= null) {Dialogclicklistener.onokclick ();
  }
   }
  }); Cancelbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {dismiss ();
    if (Dialogclicklistener!= null) {Dialogclicklistener.oncancelclick ();
 }
   }
  }); 
  private void Initwindow () {this.setbackgrounddrawable (new colordrawable (0));
  Displaymetrics d = context.getresources (). Getdisplaymetrics (); 
  This.setwidth ((int) (D.widthpixels * 0.8)); 
  This.setheight (layoutparams.wrap_content); 
  This.setfocusable (TRUE); 
  This.setoutsidetouchable (TRUE); 
 This.update ();
 public void Showatbottom (view view) {Showasdropdown (View.getwidth ()-getwidth ())/2), 20);
 public void Setondialogclicklistener (Ondialogclicklistener clicklistener) {dialogclicklistener = ClickListener;
  public interface ondialogclicklistener{void Onokclick ();
 void Oncancelclick ();

 }
}

2.3 Custom Layout

The first two are system encapsulated view, the same, we can customize the layout layout to implement the pop-up dialog box effect. Since it is a custom, it is necessary to elaborate
Confirmlayout inherits from Framelayout by getting the window manager WindowManager to add our custom view to the front end of the window and display it to achieve the desired results.

1. Initialize View

First initialize the semitransparent black background and corresponding confirm_layout, and then add a key to the form to return the event

 protected void Initialize () {
  initbackground ();//Initialize black background
  initcontentview ()//initialize confirm_layout corresponding view

  WindowManager = (WindowManager) getcontext (). Getsystemservice (Context.window_service);
  Setonkeylistener (New Onkeylistener () {///Add key to return event
   @Override public
   boolean OnKey (View v, int keycode, keyevent Event) {
    if (Keyevent.keycode_back = = KeyCode && Keyevent.action_down = = Event.getaction ()) {
     hide ();/ /Hide Current View return
     true;
    }
    return false;
   }

  Setfocusable (TRUE); Can get focus
  setfocusableintouchmode (TRUE);//Touch to get focus
 }

2. Show Custom View:show ()

When the call is displayed, it is guaranteed that in the main thread, if the current view is not added to the window, add it, and then use the animation gradient effect to display the background and the current dialog view when the animation finishes.

public void Show () {(Activity
  ) GetContext ()). Runonuithread (New Runnable () {
   @Override public
   void Run () {
    if (getparent () = null) {//Not added add to form
     //Get Layout property of form, set top left corner, fill parent container
     windowmanager.layoutparams WLP = new Windowmanager.layoutparams ();
     Wlp.type = WindowManager.LayoutParams.TYPE_APPLICATION;
     Wlp.format = pixelformat.transparent;
     wlp.gravity = Gravity.left | Gravity.top;
     Wlp.width = layoutparams.match_parent;
     Wlp.height = layoutparams.match_parent;
     Windowmanager.addview (Confirmlayout.this, WLP);
    }
    Showbackground ()//show background animation and custom View
   }}
  );

 /**
 * Display background animation */
 protected void Showbackground () {
  if (isshowing) return
   ;
  Isshowing = true;
  Background.clearanimation ();
  Background.setvisibility (view.visible);
  Alphaanimation an = new Alphaanimation (0, 1);
  An.setduration (Durationmillis);
  Background.startanimation (an);
 }

3. Hide Custom View:hide ()

The way to hide a dialog box is the opposite of Show (), which first calls the hidden animation, and the end of the animation removes view from the form

 public void Hide () {(Activity
  ) GetContext ()). Runonuithread (New Runnable () {
   @Override public
   void Run () {
    hidebackground ();//Hidden background
    if (getparent ()!= null)
     Windowmanager.removeview (confirmlayout.this); Remove View
   }}
  );

 /**
 * Hide Background background animation */
 protected void Hidebackground () {
  if (!isshowing) return
   ;
  Isshowing = false;
  Background.clearanimation ();
  Alphaanimation an = new Alphaanimation (1, 0);
  An.setduration (Durationmillis);
  An.setanimationlistener (New Animationlistener () {
   @Override public
   void Onanimationstart (Animation Animation) {
   }

   @Override public
   void Onanimationrepeat (animation animation) {
   }

   @Override Public
   void Onanimationend (Animation Animation) {
    background.setvisibility (view.gone);
   }
  });
  Background.startanimation (an);
 }

Other parts Ibid, no longer one by one posted, detailed view of the sample source code.

The dialog style of 2.4 activity

The effect that the activity is displayed as a dialog is achieved by using the theme theme. We first configure the activity in Androidmanifest.xml so that

Android:theme= "@android: Style/theme.dialog"
Also, we can add custom attributes by customizing the style style inherited from Theme.dialog, such as:

<resources>
 <style name= "Dialogstyle" parent= "@android: Style/theme.dialog" >
  <item name= " Android:windowbackground "> @android:color/transparent</item>
  <item name=" Android:windowframe " > @null </item>
  <item name= "Android:windownotitle" >true</item>
  <item name= "Android : windowisfloating ">true</item>
  <item name=" Android:windowistranslucent ">true</item>
  <item name= "Android:windowfullscreen" >true</item>
  <item name= "Android: Backgrounddimenabled ">true</item>
 </style>
</resources>

Then use the > android:theme= "@style/dialogstyle" to achieve the above effect. A specific implementation is similar to dialog:

public class Confirmactivity extends activity{private TextView Titletv,contenttv;
 Private View okbtn,cancelbtn;

 Private Ondialogclicklistener Dialogclicklistener;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Requestwindowfeature (Window.feature_no_title);
  Setcontentview (R.layout.confirm_dialog);
  Initviews ();
 Initlisteners ();
  private void Initviews () {Initwindow ();
  Titletv = (TextView) Findviewbyid (r.id.title_name);
  Contenttv = (TextView) Findviewbyid (R.id.text_view);
  OKBTN = Findviewbyid (R.ID.BTN_OK);
  CANCELBTN = Findviewbyid (R.id.btn_cancel);
    Okbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {finish ();
    if (Dialogclicklistener!= null) {Dialogclicklistener.onokclick ();
 }
   }
  });
  private void Initwindow () {GetWindow (). setbackgrounddrawable (New colordrawable (0)); GetWindow (). Setsoftinputmode (WindowManager.LayoutParams.SOFT_input_state_hidden |
 WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); private void Initlisteners () {Cancelbtn.setonclicklistener (new View.onclicklistener () {@Override public voi
    D OnClick (View v) {finish ();
    if (Dialogclicklistener!= null) {Dialogclicklistener.oncancelclick ();
 }
   }
  });
 public void Setondialogclicklistener (Ondialogclicklistener clicklistener) {dialogclicklistener = ClickListener;
  public interface ondialogclicklistener{void Onokclick ();
 void Oncancelclick ();

 }
}

2.5 dialogfragment

Dialogfragment was introduced and promoted when Android was 3.0.
When using dialogfragment, we need to implement at least Oncreateview or Oncreatedialog methods. Here in the Oncreatedialog directly back to the previous written confirmdialog to achieve this fragment.

public class Confirmfragment extends dialogfragment{

 @Override the
 @NonNull public
 Dialog Oncreatedialog ( Bundle savedinstancestate) {return
  new Confirmdialog (Getactivity ());
 }

public void Setondialogclicklistener (Ondialogclicklistener clicklistener) {(
  confirmdialog) Getdialog ()). Setondialogclicklistener (Clicklistener);
 }


It is certainly not recommended to return to the previously defined confirmdialog directly. We actually use fragment's Oncreateview is also more reasonable and brief, he can produce the same dialog effect, and can be used as an inline fragment reference. From the use of summary, Fragmentdialog compared to Dialog has two points of benefit:

When the mobile configuration changes, causing the activity to be recreated, such as a spin screen, the Dialogfragment dialog will be automatically rebuilt by the Fragmentmanager, but the dialog implementation will not be regenerated;

Dialogfragment also has the fragment advantage of being able to rollback within an activity (because Fragmentmanager manages a fallback stack and, in addition, can be nested in other layouts directly as a normal fragment;

3. Summary

From the realization of the effect that we do have a lot of choices, of course, we use the most must be a number of dialog (Fragmentdialog) and Popupwindow. However, in general, the choice of dialog and Popupwindow is determined by our specific use scenarios. For example, some of the message, more suitable for dialog, and pop-up some specific options, the need to wait for selection results, and so on, more inclined to use Popupwindow.

Several use scenes of Fragmentdialog

Several use scenes of Popupwindow

4. Supplementing

Actually there's a kind of long press the pop-up menu, which can be implemented by the View.setoncreatecontextmenu () method provided by the system, in addition to the pop-up menu option in the above method. Like what:

Itemview.setoncreatecontextmenulistener (New View.oncreatecontextmenulistener () {
    @Override public
    Void Oncreatecontextmenu (ContextMenu menu, View V, contextmenu.contextmenuinfo menuinfo) {
     menu.add ("delete"). Setonmenuitemclicklistener (New Menuitem.onmenuitemclicklistener () {
      @Override public
      Boolean Onmenuitemclick (MenuItem Item) {
       //execute delete operation return
       true;
      }
    }
   );

Long press eject, the basic effect is:

Interested may wish to try.

After that, let's take a look at the source from the point of view of the several implementation of the specific principles, and finally through some simple encapsulation to do a similar actionsheet control on the effect of iOS.
The demo effect is probably:

  

For more information, stay tuned for the next blog post.

Finally attached to the content of the source code: sample Source Demo (has been updated)

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.