The dialog box is one of the most commonly used controls in Android, and Google also provides a variety of custom dialog boxes. I think a lot of people are too vague. So let me summarize it all.
I usually project development essential framework
- The most powerful network request Net on Android
- The strongest list on Android (including StateLayout) BRV
- Android’s most powerful default page StateLayout
- JSON and long text log printing tool LogCat
- Support for asynchronous and global custom toast tool Tooltip
- Develop debug window tool DebugKit
- One line of code creates the transparent StatusBar StatusBar
Dialog box several ways to achieve:
- Activity
- Popwindow
- Dialog
- Fragment
- BottomSheet
The key class
- AlertDialog
- ProgressDialog
- DialogFragment
- Activity
- BottomSheetDialog
- BottomSheetDialogFragment
AlertDialog
Alertdialogs are the most commonly used alertdialogs.
Here’s a key class: alertDialog.Builder. Belongs to the constructor pattern usage.
The simplest dialog box is shown here
code
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setMessage("Information");
builder.show();
Copy the code
Methods to introduce
The most basic AlertDialog is described above. But more complex functionality is needed in development. So I’m going to go through all of them
Builder is an inner class belonging to the AlertDialog. The constructor responsible for creating the AlertDiglog. So it’s chained programming.
Because of the constructor pattern, you can simply ignore all the methods of the AlertDialog; the Builder already implements all the functionality. And the AlertDialog is Protected and cannot create objects directly.
Confirm and cancel/neutral buttons
It’s called the OK and cancel buttons, but you can set it to any other name or function.
builder.setPositiveButton("Sure".new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Click the callback method for the event}}); builder.setNegativeButton("Cancel".new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}});Copy the code
Left button (Cancel)
AlertDialog.Builder setPositiveButton (intTextId, / / a string array resource id DialogInterface. An OnClickListener listener)
AlertDialog.Builder setPositiveButton (CharSequence text, / / string DialogInterface. An OnClickListener listener)
Copy the code
Right button (OK)
AlertDialog.Builder setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener)
AlertDialog.Builder setNegativeButton (int textId,
DialogInterface.OnClickListener listener)
Copy the code
Neutral button (whatever you write). This button is between cancel and confirm.
AlertDialog.Builder setNeutralButton (CharSequence text, DialogInterface.OnClickListener listener)
AlertDialog.Builder setNeutralButton (int textId,
DialogInterface.OnClickListener listener)
Copy the code
Traditional selection dialog box
Note that none of the item selection methods can be used with setMessage. Otherwise it is invalid, and any item selected will close the dialog box.
AlertDialog.Builder setItems (int itemsId,
DialogInterface.OnClickListener listener)
AlertDialog.Builder setItems (CharSequence[] items, DialogInterface.OnClickListener listener)
Copy the code
MaterialDesign Radio dialog box
The difference between this dialog box and a traditional radio dialog box is that an item can be selected without automatically closing the dialog box. And you can set the items that are selected by default.
AlertDialog.Builder setSingleChoiceItems (intItemsId, // Resource array IDintCheckedItem, // Selects the index of the item in the state. If none is selected by default, write -1
DialogInterface.OnClickListener listener)
AlertDialog.Builder setSingleChoiceItems (ListAdapter adapter, // ListView adapterint checkedItem,
DialogInterface.OnClickListener listener)
AlertDialog.Builder setSingleChoiceItems (Cursor, // Use the Cursor to create the entryint checkedItem,
String labelColumn,
DialogInterface.OnClickListener listener)
AlertDialog.Builder setSingleChoiceItems (CharSequence[] items, // string array, most often simple.int checkedItem,
DialogInterface.OnClickListener listener)
Copy the code
Multiple selection dialog box
AlertDialog.Builder setMultiChoiceItems (CharSequence[] items, // array of itemsboolean[] checkedItems, // Select the status array. If you don't want any selected by default, write itnull
DialogInterface.OnMultiChoiceClickListener listener)
AlertDialog.Builder setMultiChoiceItems (int itemsId,
boolean[] checkedItems,
DialogInterface.OnMultiChoiceClickListener listener)
AlertDialog.Builder setMultiChoiceItems String isCheckedColumn, String labelColumn, String isCheckedColumn DialogInterface.OnMultiChoiceClickListener listener)
Copy the code
Parameter description:
- Items: Nothing to talk about. The content of the entry
- CheckedItems This is an array of Boolean types. The selection status of the corresponding items
- Listener Callback listener
The sample
final String[] itemTitles = {"Geoduck"."Abalone"."Peach bun"};
builder.setMultiChoiceItems(itemTitles, null.new DialogInterface.OnMultiChoiceClickListener() {
/** * calls back when a dialog entry is selected@paramDialog, which can be used to call the Dismiss close dialog * within the callback method@paramWhich Index of the currently selected item *@paramIsChecked Selected state */
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
/ / toast
Toast.makeText(MainActivity.this, itemTitles[which], Toast.LENGTH_SHORT).show();
dialog.dismiss(); // Close the dialog box}});Copy the code
Other ways to create a dialog box
These two methods are rarely used. Because it’s relatively complicated.
The same function as setMultiChoiceItems and setSingleChoiceItems.
The ListView adapter
The equivalent of the ListView adapter, the ListAdapter, is used to set the display of the selected item. Richer content can be displayed.
AlertDialog.Builder setAdapter (ListAdapter adapter, DialogInterface.OnClickListener listener)
Copy the code
Cursor Cursor
See Cursor for more details
AlertDialog.Builder setCursor (Cursor cursor, DialogInterface.OnClickListener listener, String labelColumn)
Copy the code
Create and display
AlertDialog create (a) // The creation simply returns an AlertDialog object. The dialog box will not be displayed
AlertDialog show (a) // Display the dialog directly
Copy the code
Get context
Gets the context object passed in when the AlertDialog was created.
Context getContext (a)
Copy the code
Can I cancel it?
The default is true, meaning that clicking on the outside of the dialog will close the dialog. If false, it will not be closed
AlertDialog.Builder setCancelable (boolean cancelable)
Copy the code
The title
AlertDialog.Builder setTitle (CharSequence title)
AlertDialog.Builder setTitle (int titleId)
Copy the code
The method title above is just a literal form. The following method allows you to customize any View object to display at the location of the title.
AlertDialog.Builder setCustomTitle (View customTitleView)
Copy the code
The title icon
Add a picture as an icon to the left of the title
AlertDialog.Builder setIcon (Drawable icon)
AlertDialog.Builder setIcon (int iconId)
Copy the code
There is also a topic property to set the dialog box icon. I don’t understand,
AlertDialog.Builder setIconAttribute (int attrId)
Copy the code
The custom dialog box is displayed
You can customize the dialog box to display anything. Note that even if you customize the dialog box. If you use the Settings ok and cancel buttons, they still appear;
AlertDialog.Builder setView (int layoutResId) // The layout file will do
AlertDialog.Builder setView (View view) / / the View object
Copy the code
Problem with input box:
If an EditText inserted into an AlertDialog custom View does not eject the keyboard, add the following code
Window alertDialogWindow = mAlertDialog.getWindow();
alertDialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
Copy the code
If you want to input the box automatically pops up
alertDialogWindow.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Copy the code
The listener
Cancel listener
Canceling the listener is a way of clicking outside the dialog box to close the dialog box. There is no callback when calling the dismiss method closed
AlertDialog.Builder setOnCancelListener (DialogInterface.OnCancelListener onCancelListener)
Copy the code
Turn off the listener
The listener is the one that calls back when the AlertDialog method is called in dismiss() or when a click is made outside the dialog.
AlertDialog.Builder setOnDismissListener (DialogInterface.OnDismissListener onDismissListener)
Copy the code
ListAdapter entry listener
This is the method you use when you set the ListAdapter to display the dialog entries
AlertDialog.Builder setOnItemSelectedListener (AdapterView.OnItemSelectedListener listener)
Copy the code
Key monitor
Can accept button events. Can be used to mask the button after the dialog box pops up.
AlertDialog.Builder setOnKeyListener (DialogInterface.OnKeyListener onKeyListener)
Copy the code
conclusion
If you don’t need any of the AlertDialog elements (buttons/titles/click events) at all, you can inherit the Dialog custom implementation. Of course, I don’t recommend emulating the IOS Dialog;
If you’re using a completely custom dialog I would recommend a DialogFragment (which I’ll talk about later)
Qi Yin skills
Automatic eject keyboard
Dialog If there is an input box that cannot automatically pop up the keyboard, the following function can be implemented;
public static void showInputMethod(EditText editText) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) Library.getApp()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm ! =null) { imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); }}Copy the code
Set the list divider
AlertDialog can set lists, but there is no function to set separators;
public static void setDivider(AlertDialog dialog, @DrawableRes int divider) {
ListView listView = dialog.getListView();
if(listView ! =null) {
listView.setOverscrollFooter(newColorDrawable(Color.TRANSPARENT)); listView.setDivider(Res.getDrawable(divider)); }}Copy the code
The background transparent
public static void setTransparent(Dialog dialog) {
Window window = dialog.getWindow();
if(window ! =null) { window.setBackgroundDrawableResource(android.R.color.transparent); }}Copy the code
Set the dialog box size
-
DialogFragment Setting the subject. Disadvantages: Force the maximum width
dialog.setStyle( androidx.fragment.app.DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog_MinWidth ) Copy the code
-
Wrap the layout one more layer. Because the top-level size of DialogFragment is invalid, but Dialog is not. Disadvantages: You can only set fixed values
-
Disadvantages of setting Window layout parameters: only fixed values can be set
Dialog has a default width, height is package-appropriate; But sometimes you need control; Be sure to execute the following function after the dialog is displayed;
ProgressDialog
In addition to the use of the warning dialog above. A separate dialog style is also provided. Progress bar dialog box. Progress bar is a great invention in the history of computer applications.
ProgressDialog progressDialog = new ProgressDialog(this);// Create the progress dialog object
progressDialog.setTitle("Title"); // Set the title
progressDialog.setMessage("Loading..."); // Set the message
progressDialog.show(); // Display the progress bar
Copy the code
In addition to the above default progress bar style, Google also provides a set style horizontal progress bar
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// ProgressDialog.style_spinner Rotates the progress bar. This is the default style
Copy the code
Methods to introduce
ProgressDialog is a subclass of AlertDialog. Inherits all of its methods. So I’m just going to talk about the new method.
Schedule set
Since it is a progress dialog, of course, there is a way to set progress. The default rotation progress bar style does not set progress. This method must be executed after show() to take effect.
int getProgress (a)
void setProgress (int value)
Copy the code
The biggest progress
void setMax (int max)
int getMax (a)
Copy the code
According to
You can use the superclass’s show() method. You can also use the new static method on the ProgressDialog to display it in a single line of code. Like Toast.
ProgressDialog show (Context Context, // Context CharSequence title, // title CharSequence message) // Message content
ProgressDialog show (Context context,
CharSequence title,
CharSequence message,
boolean indeterminate)
ProgressDialog show (Context context,
CharSequence title,
CharSequence message,
boolean indeterminate,
boolean cancelable)
ProgressDialog show (Context context,
CharSequence title,
CharSequence message,
boolean indeterminate,
boolean cancelable,
DialogInterface.OnCancelListener cancelListener)
Copy the code
The secondary progress
Similar to the cache progress bar when you watch a video. Lighter than the main progress bar.
void setSecondaryProgress (int secondaryProgress)
int getSecondaryProgress (a)
Copy the code
Growth progress
The difference with setProgress is that the change is to add or subtract from the original progress. And it doesn’t matter if it’s before or after the show() method.
void incrementProgressBy (int diff) // Progress increased
void incrementSecondaryProgressBy (int diff) // Secondary progress increased
Copy the code
Uncertain status progress bar
This effect applies only to horizontal progress bars. The status of the progress bar is constantly changing.
void setIndeterminate (boolean indeterminate) // The default is false. True
boolean isIndeterminate (a) // Whether it is in an uncertain state
void setIndeterminateDrawable (Drawable d) // Set an image as an indeterminate progress display
Copy the code
Progress of the style
void setProgressStyle (int style)
Copy the code
Includes two parameters:
- STYLE_HORIZONTAL Progress bar
- STYLE_SPINNER Ring progress bar
Setting the progress picture
This method is only valid if the ProgressDialog is horizontal.
void setProgressDrawable (Drawable d)
Copy the code
Progress display formatting
void setProgressNumberFormat (String format)
Copy the code
Use a string to format the text content in the bottom right corner of the progress dialog. If NULL is passed, nothing is displayed.
%1d: current progress percentage
% 2D: maximum progress percentage
For example, if you want to display the size of the download (in KB), you can write this
setProgressNumberFormat("%1dkb/%2dkb")
Copy the code
Of course you can write anything you want
The progress bar percentage is formatted
There’s a class called NumberFormat, which is a tool for formatting numbers. Abstract classes need to create objects through the getInstance**() method. There are a few more methods in this class that I won’t go through in detail. This percentage format is also used less.
Parameter null, the percentage in the lower left corner of the progress bar will not be displayed.
void setProgressPercentFormat (NumberFormat format)
Copy the code
Example:
// getCurrencyInstance is a currency format method
dialog.setProgressPercentFormat(NumberFormat.getCurrencyInstance());
Copy the code
ProgressBar
A ProgressBar is a ProgressBar used as a control. It can only be used in the layout file. A ProgressDialog is implemented by creating a View display that contains the ProgressDialog.
The progress bar dialog can also be written directly to the layout file as a control, and the class will only be displayed if it is used in the layout. Horizontal progress style provided by the system. StyleProgressBar.Horizontal
<ProgressBar
style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
android:progress="50"
android:max="100"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/
/>
Copy the code
By the way, the progress bar cannot be opened on the child thread (show) but can be closed on the child thread (dismiss).
DialogFragment
This class is a subclass of Fragment and is an official recommended dialog.
I recommend DialogFragment for dialog content that needs customization. The default altertDialog is recommended for normal dialogs. The ios effect wheel control is strongly not recommended. What’s the design, ugly and inconvenient
Use it the same way as regular fragments.
public class CustomDialogFragment extends DialogFragment {
/** * is the same as the onCreate method for the Fragment@param inflater
* @param container
* @param savedInstanceState
* @returnReturns the View object */
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
/** * use one of the above methods to nest dialogs in a Fragment. ** if both methods are written, only this method will work@param savedInstanceState
* @returnReturn the Dialog object */
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return super.onCreateDialog(savedInstanceState); }}Copy the code
Display in the Activity
new CustomDialogFragment().show(getSupportFragmentManager(), "bag");
Copy the code
※ If the DialogFragment is onCreateView. The root layout of the layout file, whether match_parent or the given value, counts as wrAP_content. To control the size of the dialog, write the subcontainer layout.
The DialogFragment cannot be displayed in full screen
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="The Program Daniel Wu"
/>
</RelativeLayout>
</RelativeLayout>
Copy the code
Declarative cycle method
This is all about periodic callback methods for overrides. Note that DialogFragment is a subclass of Fragment. Includes all life cycles of the Fragment
Shut down
Calls back when the Dismiss method closes the dialog box
void onDismiss (DialogInterface dialog)
Copy the code
cancel
Click DialogFragment to cancel the DialogFragment callback method
void onCancel (DialogInterface dialog)
Copy the code
A method is called
Method used for invocation
Display dialog
- Common usage shows DialogFragment, which is nested in the Activity as a common Fragment
- Use the following method to pop up the DialogFragment as a dialog box
void show (FragmentManager manager, String tag) // This parameter can be read by anyone with Fragment knowledge.
int show (FragmentTransaction transaction, String tag)
Copy the code
Close dialog
void dismiss (a)
Copy the code
Can I cancel it?
Click on the outside of the dialog box can close the dialog box
void setCancelable (boolean cancelable)
boolean isCancelable (a)
Copy the code
Get the dialog object
Dialog getDialog (a) // Get the Dialog object returned by the onCreateDialog method
Copy the code
Whether to display as a dialog box
If set to false, it will create a layout rather than a dialog, just like the Fragment. This method needs to be executed before the onCreateDialog method to be valid. It is recommended to do this in the onCreate method. However, if you set this to false, the DialogFragment show method will not work.
It’s not going to work.
boolean getShowsDialog (a)
void setShowsDialog (boolean showsDialog) // Defaults to true
Copy the code
The theme style
Must be called before the onCreateDialog method executes. That’s called inside the onCreate method.
void setStyle (intStyle, / / styleint theme) // Theme, if 0, the default theme is used
Copy the code
Style supports four parameter values:
- STYLE_NORMAL ordinary
- STYLE_NO_FRAME without borders
- STYLE_NO_INPUT cannot get focus. You will not be able to type or click
- STYLE_NO_TITLE no title
Get the topic of the DialogFragment
Corresponds to the theme set by the setStyle() method.
int getTheme ()
Copy the code
Cancel state loss
See the commitAllowingStateLoss method of the Fragment for details
void dismissAllowingStateLoss ()
Copy the code
About width being limited to range
SetStyle (dialogfragment.style_no_title, android.r.stile. Theme_Holo_Light_Dialog_MinWidth); / / transparent background getDialog (.) getWindow () setBackgroundDrawableResource (android. R.c olor. Transparent);Copy the code
Activity
Activity as a dialog box. Just inherit the dialog’s topic in the topic. Then start the activity normally.
The sample
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
</style>
Copy the code
Here I have removed the title bar and background transparency.
※ Do not set the root layout of the activity to match_parent full screen.
BottomSheetDialog
Internet version 23.2.0
The sample code
public class MainActivity extends AppCompatActivity {
private BottomSheetDialog mDialog;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mDialog = new BottomSheetDialog(this);
mDialog.setContentView(R.layout.dialog_bottom_sheet);
}
@OnClick(R.id.button) public void onClick(a) { mDialog.show(); }}Copy the code
Dialog creation requires code to build instance objects without further explanation
A constructor
BottomSheetDialog(Context context)
BottomSheetDialog(Context context, int theme)
Copy the code
Setting options
void setCanceledOnTouchOutside(boolean cancel) // Cancel the dialog box out of touch range
void setCancelable(boolean cancelable) // The dialog cannot be cancelled outside the return key and touch range
// Set the contents of the dialog
void setContentView(View view)
void setContentView(int layoutResId)
void setContentView(View view, ViewGroup.LayoutParams params)
Copy the code
BottomSheetFragment
Front introduced DialogFragment. Here mentioned BottomSheetDialogFragment usage. No other introduction.
BottomSheetBehavior
Just pull dialog is too simple, Android provides CoordinatorLayout. The behaviors of the implementation class BottomSheetBehavior to match CoordinatorLayout layout is used. Achieve a more beautiful MaterialDesign interaction effect.
The difference between the BottomSheet dialog and the BottomSheet dialog is that it supports a richer set of BottomSheet properties.
The sample
layout
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jiuxing.bottomsheet.MainActivity"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open"
/>
</LinearLayout>
<LinearLayout
app:behavior_peekHeight="60dp"
app:behavior_hideable="true"
app:behavior_skipCollapsed="false"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="500dp"
android:background="@color/colorPrimary"
android:orientation="vertical"
app:layout_behavior="@string/bottom_sheet_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
Copy the code
code
public class MainActivity extends AppCompatActivity {
private BottomSheetBehavior<View> mBottomSheetBehavior;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.rl));
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
@OnClick(R.id.button) public void onClick(a) { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); }}Copy the code
methods
void setHideable (boolean hideable) // Whether to hide
void setPeekHeight (int peekHeight) // Fold height, which is the height fixed at the bottom of the screen when pulled down
void setSkipCollapsed (boolean skipCollapsed) // Do not fold, completely hide
void setState (int state) // Set the current Behavior state
Copy the code
BottomSheetBehavior has five states:
- STATE_COLLAPSED shows part of the height of state (folded state) the default state
- STATE_EXPANDED Expansion status
- STATE_HIDDEN Indicates the hidden state
- STATE_DRAGGING is dragging
- State_demystified to slide
Tip: Some states are in-process states, and setting them directly via setState is invalid. For example, dragging the state
attribute
android.support.design:behavior_hideable // Whether all can be hidden. The default is false. If set to true, the default state is hidden
android.support.design:behavior_peekHeight // Minimum fold height
android.support.design:behavior_skipCollapsed // If true. Drag down to hide instead of folding (hideable is true)
Copy the code
State change callback
void setBottomSheetCallback (BottomSheetBehavior.BottomSheetCallback callback)
Copy the code
The sample
mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
/ * * *@param bottomSheet
* @paramNewState Current state */
@Override public void onStateChanged(@NonNull View bottomSheet, int newState) {}/ * * *@param bottomSheet
* @paramSlideOffset drag is coordinate offset */
@Override public void onSlide(@NonNull View bottomSheet, float slideOffset) {}})Copy the code
conclusion
Features:
- Dialog
- Meets common dialog box requirements
- The most commonly used
- DialogFragment
- Dialog, essentially
- Dialog boxes for complex logic
- Has the Fragment feature and can be used as a common Fragment
- Activity
- It can be really full screen
- Built-in animation
- popwindow
- Can be attached to other controls.
- Customize the display location
- BottomSheet
- It can be used in conjunction with CoordinatorLayout, which has gesture swiping and animation effects laid out at the bottom