The method of customizing dialog in builder mode in Android _android

Source: Internet
Author: User
Tags static class visibility

Objective

The needs of our developers in the actual project are varied, and sometimes we have to match the app's own design style, and sometimes we feel that the system's dialog box is not very free, so it's necessary to define a dialog for yourself.

Why use the builder mode

The builder design pattern is a step-by-step creation pattern for creating a complex object that allows users to more granular control over the construction process of an object without knowing the internal build details. Its advantage lies in the separation and decoupling of the object's construction and representation. We all know that the Android system's own dialog box, such as Alertdialog, uses the builder mode, so the visible builder model is ideal for building dialog objects.

The following words do not say much, on the code.

Basedialog.java

Package com.acker.android.dialog;
Import Android.app.Dialog;
Import Android.content.Context;
Import Android.os.Bundle;
Import Android.text.TextUtils;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.FrameLayout;
Import Android.widget.LinearLayout;
Import Android.widget.ProgressBar;

Import Android.widget.TextView;
  /** * Custom Dialog base class * * @author Guojinyu/public class Basedialog extends Dialog {private TextView tvtitle;
  Private TextView tvmsg;
  Private ProgressBar pbloading;
  Private Button btnpositive;
  Private Button btnnegative;
  Private Framelayout Flcustom; Private View.onclicklistener Ondefaultclicklistener = new View.onclicklistener () {@Override public void OnClick (
    View view) {cancel ();
  }

  };
  Private View.onclicklistener Onpositivelistener = Ondefaultclicklistener;
  Private View.onclicklistener Onnegativelistener = Ondefaultclicklistener;
  Private String Mtitle;
  Private String mmessage; Private StringPositivetext;
  Private String Negativetext;
  Private Boolean isprogressbarshow = false;
  Private Boolean isnegativebtnshow = true;

  Private View Mview;
  Private Basedialog {Super (context, r.style.mydialog);
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.dialog_base);
    Flcustom = (framelayout) Findviewbyid (r.id.fl_dialog_content);
    Tvtitle = (TextView) Findviewbyid (r.id.tv_title);
    pbloading = (ProgressBar) Findviewbyid (r.id.pb_loading);
    Tvmsg = (TextView) Findviewbyid (r.id.tv_msg);
    Btnpositive = (Button) Findviewbyid (r.id.btn_positive);
  Btnnegative = (Button) Findviewbyid (r.id.btn_negative);
    /** * The method to display the dialog box after the Builder class's Create () method is called * * @Override public void Show () {super.show ();
  Show (this); } private void Show (Basedialog mdialog) {if (! Textutils.isempty (Mdialog.mtitle)) {MDialog.tvTitle.setText (Mdialog.mtitle);
      } if (Mdialog.mview!= null) {MDialog.flCustom.addView (Mdialog.mview);
      MDialog.pbLoading.setVisibility (View.gone);
    MDialog.tvMsg.setVisibility (View.gone); } else {if (!
        Textutils.isempty (Mdialog.mmessage)) {mDialog.tvMsg.setText (mdialog.mmessage);
      MDialog.tvMsg.setVisibility (view.visible);
        } if (isprogressbarshow) {mDialog.pbLoading.setVisibility (view.visible);
        MDialog.btnPositive.setVisibility (View.gone);
      MDialog.btnNegative.setVisibility (View.gone);
      } if (!mdialog.isnegativebtnshow) {mDialog.btnNegative.setVisibility (view.gone);
      Linearlayout.layoutparams layoutparams = (linearlayout.layoutparams) mdialog.btnpositive. GetLayoutParams ();
      Layoutparams.setmargins (Layoutparams.topmargin, Layoutparams.bottommargin);
    MDialog.btnPositive.setLayoutParams (Layoutparams); else {MDialog.btnNegative.setOnClickListener (Mdialog.onnegatIvelistener); if (!
      Textutils.isempty (Mdialog.negativetext)) {mDialog.btnNegative.setText (mdialog.negativetext);
    } mDialog.btnPositive.setOnClickListener (Mdialog.onpositivelistener); if (!
    Textutils.isempty (Mdialog.positivetext)) {mDialog.btnPositive.setText (mdialog.positivetext);

    } public static class Builder {private Basedialog mdialog;
    Public Builder {mdialog = new Basedialog (context); /** * Set Dialog Title * * @param title */Public Builder Settitle (String title) {MDIALOG.MTI
      tle = title;
    return this; /** * Sets the dialog text content, if the Setview () method is invoked, the item fails * * @param msg/public Builder setmessage (String ms
      g) {mdialog.mmessage = msg;
    return this; /** * Set the callback of the confirmation button * * @param onclicklistener * * * public Builder Setpositivebutton (View.onclick Listener onclicklistener) {Mdialog.onpositivelistenER = Onclicklistener;
    return this; /** * Set the callback of the confirmation button * * @param btntext,onclicklistener * * * public Builder Setpositivebutton (stri
      Ng Btntext, View.onclicklistener onclicklistener) {mdialog.positivetext = Btntext;
      Mdialog.onpositivelistener = Onclicklistener;
    return this; /** * Set Cancel button back off * * @param onclicklistener/public Builder Setnegativebutton (View.onclick
      Listener onclicklistener) {mdialog.onnegativelistener = Onclicklistener;
    return this; /** * Set callback for Cancel button * * @param btntext,onclicklistener/public Builder Setnegativebutton (stri
      Ng Btntext, View.onclicklistener onclicklistener) {mdialog.negativetext = Btntext;
      Mdialog.onnegativelistener = Onclicklistener;
    return this; /** * Set Hand no display ProgressBar, default does not show * * @param isprogressbarshow/public Builder Setprogressbar
Show (Boolean isprogressbarshow) {      Mdialog.isprogressbarshow = Isprogressbarshow;
    return this; /** * Sets whether to display the Cancel button, the default display * * @param isnegativebtnshow/public Builder setnegativebtnshow (boo
      Lean isnegativebtnshow) {mdialog.isnegativebtnshow = Isnegativebtnshow;
    return this; /** * Set Custom content View * * @param view/Public Builder Setview (view view) {Mdialog.mvie
      w = view;
    return this; /** * Set the dialog can be cancel, by default, * * @param cancelable/Public Builder setcancelable (Boolean C
      ancelable) {mdialog.setcancelable (cancelable);
    return this; The/** * Settings dialog box is called by the callback interface, and the Cancel () method is invoked to callback the interface * * @param oncancellistener/Public Build
      Er setoncancellistener (oncancellistener oncancellistener) {mdialog.setoncancellistener (OnCancelListener);
    return this;
 The/** * Settings dialog disappears the corresponding callback interface, and all the dialog boxes disappear will callback the interface * * @param ondismisslistener    * * Public Builder Setondismisslistener (Ondismisslistener ondismisslistener) {Mdialog.setondismisslistener (o
      Ndismisslistener);
    return this;
    /** * The method to construct the dialog box after setting the properties of the Builder class/public Basedialog Create () {return mdialog; }
  }
}

The code is simple, the Basedialog class defines some of the controls that a dialog box will display and some properties that correspond to those controls, and the method that eventually fills all the properties into the control show() . The builder class is an internal class of Basedialog that defines the set method for all properties of the Basedialog class and the method after the assembly is completed create() .

The layout file for the corresponding custom dialog dialog_base.xml is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" Android:
    background= "@drawable/bg_base_dialog" android:orientation= "vertical" > <textview android:id= "@+id/tv_title"
    Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_marginbottom= "10DP" android:layout_margintop= "10DP" android:gravity= "center" android:textcolor= "@android: Color/black" Android:te Xtsize= "18sp"/> <view android:layout_width= "match_parent" android:layout_height= "1DP" android:backgr Ound= "@android: Color/black"/> <linearlayout android:layout_width= "match_parent" android:layout_height= "W Rap_content "android:layout_marginleft=" 20DP "android:layout_marginright=" 20DP "android:orientation=" Horizonta
     L "> <progressbar Android:id= "@+id/pb_loading" android:layout_width= "wrap_content" android:layout_height= "Match_parent" a ndroid:layout_gravity= "center" android:layout_marginbottom= "20DP" android:layout_marginright= "20DP" Andr oid:layout_margintop= "20DP" android:visibility= "Gone"/> <textview android:id= "@+id/tv_msg" a
      Ndroid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_gravity= "center"
      Android:layout_marginbottom= "20DP" android:layout_margintop= "20DP" android:textcolor= "@android: Color/black" Android:textsize= "18SP" android:visibility= "Gone"/> </LinearLayout> <framelayout android:i D= "@+id/fl_dialog_content" android:layout_width= "match_parent" android:layout_height= "Wrap_content" ></ framelayout> <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" a ndroid:orientation= "Horizontal"> <button android:id=" @+id/btn_negative "android:layout_width=" 0DP "android:layout_height=" 4 0DP "android:layout_marginbottom=" 20DP "android:layout_marginleft=" 20DP "android:layout_marginright=" 20d P "android:layout_weight=" 1 "android:background=" @drawable/bg_dialog_btn_negative "android:gravity=" cent Er "android:text=" cancels "android:textcolor=" @android: Color/white "android:textsize=" 18sp "/> <bu Tton android:id= "@+id/btn_positive" android:layout_width= "0DP" android:layout_height= "40DP" Androi D:layout_marginbottom= "20DP" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" Android: layout_weight= "1" android:background= "@drawable/bg_dialog_btn_positive" android:gravity= "Center" Android : text= "OK" android:textcolor= "@android: Color/white" android:textsize= "18sp"/> </LinearLayout> ;/linearlayout>

The other resource documents involved are as follows:

dialog box Style Styles.xml

<resources>
  <!--global Dialog style-->
  <style name= "Mydialog" 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:background" > @android:color/transparent</item>
    <item name= "android:backgrounddimenabled" >true</item>
  </style>
</resources>

By setting these properties, you can ensure that the dialog box has a transparent background and no black edges.

Determine the color value of the Cancel button colors.xml

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
  <color name= "Btn_dialog_negative_normal "> #ff0000 </color>
  <color name=" btn_dialog_negative_pressed "> #bf0000 </color>
  < Color name= "Btn_dialog_positive_normal" > #368bff </color>
  <color name= "btn_dialog_positive_pressed "> #0067f3 </color>
</resources>

dialog box Background bg_base_dialog.xml

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:shape=" Rectangle >
 <corners android:radius= "4DP"/>
 <solid android: Color= "@android: Color/white"/>
 <stroke
   android:width= "1DP"
   android:color= "#e5e7ea"/>
</shape>

Contains background, rounded corners, shadow effects.

OK button Background Bg_dialog_btn_positive.xml

<?xml version= "1.0" encoding= "UTF-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android >
  <item android:drawable= "@color/btn_dialog_positive_normal" android:state_pressed= "false" > </item>
  <item android:drawable= "@color/btn_dialog_positive_pressed" android:state_pressed= "true" ></item>
</selector>

Contains the normal and pressed effects.

Cancel button Background Bg_dialog_btn_negative.xml

<?xml version= "1.0" encoding= "UTF-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android >
  <item android:drawable= "@color/btn_dialog_negative_normal" android:state_pressed= "false" > </item>
  <item android:drawable= "@color/btn_dialog_negative_pressed" android:state_pressed= "true" ></item>
</selector>

Contains the normal and pressed effects.

That's all the content of the entire custom dialog, and then we'll show you how to use it with a simple demo.

Mainactivity.java

Package com.acker.android.dialog;
Import Android.content.DialogInterface;
Import Android.os.Bundle;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;

Import Android.widget.Toast;

  public class Mainactivity extends appcompatactivity {basedialog dialog;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main); dialog = new Basedialog.builder (this). Settitle ("title"). Setmessage ("Content"). Setpositivebutton ("haha", new View.onclicklis
          Tener () {@Override public void OnClick (view view) {Dialog.dismiss (); }). Setoncancellistener (New Dialoginterface.oncancellistener () {@Override public void Oncanc
          El (Dialoginterface dialoginterface) {toast.maketext (Mainactivity.this, "Cancel", Toast.length_short). Show (); }). Setondismisslistener (New Dialoginterface.ondismisslistener ({@Override public void Ondismiss (Dialoginterface dialoginterface) {Toast.maketext (Main
          Activity.this, "dismiss", Toast.length_short). Show ();
    ). Create ();
  Dialog.show (); }

}

Look at the effect chart:


Very ugly there is wood, but it doesn't matter, here we just show its usage, how to make the dialog box to do a good job of watching you play. It can be seen that the usage of custom basedialog is basically consistent with the alertdialog of Andorid itself, and it is constructed through its builder class.

The custom dialog box also supports the ability to display ProgressBar and custom content fills.

Display ProgressBar and the touch screen is not canceled:

. Setprogressbarshow (True)
. Setcancelable (False)

The effect chart is as follows:


Custom content area and do not show Cancel button:

View view = Getlayoutinflater (). Inflate (r.layout.dialog_input_amount, null);
Final EditText Amountedit = (edittext) View.findviewbyid (r.id.dialog_et_amount);
Amountedit.settext ("123456789");
. Setview (view)
Setnegativebtnshow (False)

Its corresponding layout file is Dialog_input_amount.xml:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
  android:layout_width= "Match_ Parent "
  android:layout_height=" wrap_content "
  android:orientation=" vertical ">

  <edittext
    Android:id= "@+id/dialog_et_amount"
    android:layout_width= "match_parent"
    android:layout_height= "40DP"
    android:layout_marginbottom= "20DP"
    android:layout_marginleft= "20DP"
    android:layout_marginright= " 20DP "
    android:layout_margintop=" 20DP "
    android:gravity=" center_vertical "
    android:paddingleft=" 10DP "
    android:paddingright=" 10DP "
    android:inputtype=" Numberdecimal "
    android:singleline=" true "
    android:textsize= "18SP" >
  </EditText>

</LinearLayout>

The effect chart is as follows:

Summarize

Through this article can be seen through the Builder Mode Customization dialog can maintain the original Android dialog box, while the use of convenient, more freedom, everyone can according to their own needs to make corresponding changes to the code. What needs to be explained is that this article does not strictly follow the traditional builder design pattern to implement the dialog box, but did some simplification to more suitable for our scene. That's the whole story, and hopefully the content of this article will help Android developers.

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.