Android Studio Alert Dialog Dont Show Again

Overview

DialogFragment is a specialized Fragment used when you lot want to display an overlay modal window inside an activity that floats on height of the residue of the content.

This is typically used for displaying an alert dialog, a ostend dialog, or prompting the user for information within an overlay without having to switch to another Action.

DialogFragment is now the canonical way to display overlays; using Dialog straight is considered bad practice.

Usage

The minimum that must exist implemented when creating a DialogFragment is either the onCreateView method or the onCreateDialog method. Apply onCreateView when the entire view of the dialog is going to exist divers via custom XML. Utilise onCreateDialog when you just demand to construct and configure a standard Dialog class (such equally AlertDialog) to display.

Note: The entire guide below requires every fragment related class imported to use the androidx.fragment.app namespace and non the android.app namespace. If any imported class (FragmentManager, DialogFragment, etc) uses the android.app namespace, compile-time errors will occur.

Custom View

Allow's get-go by providing the code for creating a completely custom dialog based on an XML view. Start, an case fragment XML file in res/layout/fragment_edit_name.xml:

                      <!-- fragment_edit_name.xml -->            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:id=            "@+id/edit_name"            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            android:layout_gravity=            "middle"            android:orientation=            "vertical"            >            <TextView            android:id=            "@+id/lbl_your_name"            android:text=            "Your name"            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            />            <EditText            android:id=            "@+id/txt_your_name"            android:layout_width=            "match_parent"            android:layout_height=            "wrap_content"            android:inputType=            "text"            android:imeOptions=            "actionDone"            />            </LinearLayout>                  

and defining the fragment itself extending from the back up version of dialog fragment:

                      import            androidx.fragment.app.DialogFragment            ;            // ...                        public            class            EditNameDialogFragment            extends            DialogFragment            {            individual            EditText            mEditText            ;            public            EditNameDialogFragment            ()            {            // Empty constructor is required for DialogFragment                        // Make sure non to add together arguments to the constructor                        // Apply `newInstance` instead as shown beneath                        }            public            static            EditNameDialogFragment            newInstance            (            String            title            )            {            EditNameDialogFragment            frag            =            new            EditNameDialogFragment            ();            Bundle            args            =            new            Bundle            ();            args            .            putString            (            "title"            ,            title            );            frag            .            setArguments            (            args            );            return            frag            ;            }            @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Package            savedInstanceState            )            {            return            inflater            .            inflate            (            R            .            layout            .            fragment_edit_name            ,            container            );            }            @Override            public            void            onViewCreated            (            View            view            ,            @Nullable            Parcel            savedInstanceState            )            {            super            .            onViewCreated            (            view            ,            savedInstanceState            );            // Go field from view                        mEditText            =            (            EditText            )            view            .            findViewById            (            R            .            id            .            txt_your_name            );            // Fetch arguments from bundle and set up championship                        String            title            =            getArguments            ().            getString            (            "title"            ,            "Enter Proper name"            );            getDialog            ().            setTitle            (            title            );            // Show soft keyboard automatically and request focus to field                        mEditText            .            requestFocus            ();            getDialog            ().            getWindow            ().            setSoftInputMode            (            WindowManager            .            LayoutParams            .            SOFT_INPUT_STATE_VISIBLE            );            }            }                  

and showing the dialog in an Action extending AppCompatActivity:

                      // Note: `FragmentActivity` works here likewise                        public            class            DialogDemoActivity            extends            AppCompatActivity            {            @Override            public            void            onCreate            (            Bundle            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            setContentView            (            R            .            layout            .            main            );            showEditDialog            ();            }            private            void            showEditDialog            ()            {            FragmentManager            fm            =            getSupportFragmentManager            ();            EditNameDialogFragment            editNameDialogFragment            =            EditNameDialogFragment            .            newInstance            (            "Some Championship"            );            editNameDialogFragment            .            evidence            (            fm            ,            "fragment_edit_name"            );            }            }                  

For this to work properly make certain that all the fragment related items (FragmentDialog) are from the androidx.fragment.app namespace.

Build Dialog

2d, let's take a wait at how to build a dialog simply by customizing the bachelor Dialog objects that we can construct. For more details about the unlike types of dialogs, check out the "Things to Annotation" department below.

                      course            MyAlertDialogFragment            extends            DialogFragment            {            public            MyAlertDialogFragment            ()            {            // Empty constructor required for DialogFragment                        }            public            static            MyAlertDialogFragment            newInstance            (            String            title            )            {            MyAlertDialogFragment            frag            =            new            MyAlertDialogFragment            ();            Bundle            args            =            new            Bundle            ();            args            .            putString            (            "title"            ,            championship            );            frag            .            setArguments            (            args            );            return            frag            ;            }            @Override            public            Dialog            onCreateDialog            (            Bundle            savedInstanceState            )            {            String            title            =            getArguments            ().            getString            (            "title"            );            AlertDialog            .            Builder            alertDialogBuilder            =            new            AlertDialog            .            Builder            (            getActivity            ());            alertDialogBuilder            .            setTitle            (            championship            );            alertDialogBuilder            .            setMessage            (            "Are yous certain?"            );            alertDialogBuilder            .            setPositiveButton            (            "OK"            ,            new            DialogInterface            .            OnClickListener            ()            {            @Override            public            void            onClick            (            DialogInterface            dialog            ,            int            which            )            {            // on success                        }            });            alertDialogBuilder            .            setNegativeButton            (            "Cancel"            ,            new            DialogInterface            .            OnClickListener            ()            {            @Override            public            void            onClick            (            DialogInterface            dialog            ,            int            which            )            {            if            (            dialog            !=            goose egg            &&            dialog            .            isShowing            ())            {            dialog            .            dismiss            ();            }            }            });            return            alertDialogBuilder            .            create            ();            }            }                  

and to display the alert dialog in an activity extending AppCompatActivity:

                      public            form            DialogDemoActivity            extends            AppCompatActivity            {            @Override            public            void            onCreate            (            Package            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            setContentView            (            R            .            layout            .            main            );            showAlertDialog            ();            }            private            void            showAlertDialog            ()            {            FragmentManager            fm            =            getSupportFragmentManager            ();            MyAlertDialogFragment            alertDialog            =            MyAlertDialogFragment            .            newInstance            (            "Some title"            );            alertDialog            .            show            (            fm            ,            "fragment_alert"            );            }            }                  

Passing Data to Activeness

To pass data from a dialog to an Activity, use the same approach y'all would use for any fragment which is creating a custom listener. In short, you will need to practise the following:

  1. Define an interface with methods that can be invoked to pass data outcome to the activity
  2. Setup a view event which invokes the custom listener passing data through the method
  3. Implement the interface in the Activity defining behavior for when the event is triggered

This case below demonstrates how to laissez passer a data upshot back to the activity when the "Done" push button is pressed on the keyboard but this works similarly for other cases or for the AlertDialog (only use the listeners defined for each of the buttons):

                      public            class            EditNameDialogFragment            extends            DialogFragment            implements            OnEditorActionListener            {            private            EditText            mEditText            ;            // ane. Defines the listener interface with a method passing back data result.                        public            interface            EditNameDialogListener            {            void            onFinishEditDialog            (            Cord            inputText            );            }            // ...                        @Override            public            void            onViewCreated            (            View            view            ,            @Nullable            Bundle            savedInstanceState            )            {            // ...                        // ii. Setup a callback when the "Done" button is pressed on keyboard                        mEditText            .            setOnEditorActionListener            (            this            );            }            // Fires whenever the textfield has an action performed                        // In this case, when the "Done" button is pressed                        // REQUIRES a 'soft keyboard' (virtual keyboard)                        @Override            public            boolean            onEditorAction            (            TextView            v            ,            int            actionId            ,            KeyEvent            event            )            {            if            (            EditorInfo            .            IME_ACTION_DONE            ==            actionId            )            {            // Return input text back to activity through the implemented listener                        EditNameDialogListener            listener            =            (            EditNameDialogListener            )            getActivity            ();            listener            .            onFinishEditDialog            (            mEditText            .            getText            ().            toString            ());            // Close the dialog and return back to the parent activeness                        dismiss            ();            return            truthful            ;            }            return            fake            ;            }            }                  

and have the activity define the activeness to take when the dialog has the information:

                      public            class            DialogDemoActivity            extends            AppCompatActivity            implements            EditNameDialogListener            {            // ...                        // three. This method is invoked in the activity when the listener is triggered                        // Access the data result passed to the action here                        @Override            public            void            onFinishEditDialog            (            Cord            inputText            )            {            Toast            .            makeText            (            this            ,            "Hi, "            +            inputText            ,            Toast            .            LENGTH_SHORT            ).            testify            ();            }            }                  

Notation: setOnEditorActionListener used higher up to dismiss requires the utilise of the soft keyboard in the emulator which can exist enabled through AVD or past testing on a device. If you don't want to enable soft keyboard, you may want to dismiss on a button click or on a keypress instead.

Passing Data to Parent Fragment

In certain situations, the a dialog fragment may be invoked inside the context of some other fragment. For example, a screen has tabs with a class contained in a fragment. The course has an input for selecting dates using a date picker in a dialog. In this case, nosotros may want to pass the date back not to the activeness but instead to the parent fragment. This information can be passed back straight to the parent fragment:

                      import            androidx.fragment.app.DialogFragment            ;            public            class            EditNameDialogFragment            extends            DialogFragment            {            // Defines the listener interface                        public            interface            EditNameDialogListener            {            void            onFinishEditDialog            (            String            inputText            );            }            // Telephone call this method to send the data back to the parent fragment                        public            void            sendBackResult            ()            {            // Notice the utilize of `getTargetFragment` which will be ready when the dialog is displayed                        EditNameDialogListener            listener            =            (            EditNameDialogListener            )            getTargetFragment            ();            listener            .            onFinishEditDialog            (            mEditText            .            getText            ().            toString            ());            dismiss            ();            }            }                  

And so the dialog must exist displayed within a parent fragment passing the target via setTargetFragment with:

                      import            androidx.fragment.app.Fragment            ;            public            grade            MyParentFragment            extends            Fragment            implements            EditNameDialogListener            {            // Call this method to launch the edit dialog                        private            void            showEditDialog            ()            {            FragmentManager            fm            =            getFragmentManager            ();            EditNameDialogFragment            editNameDialogFragment            =            EditNameDialog            .            newInstance            (            "Some Title"            );            // SETS the target fragment for employ later when sending results                        editNameDialogFragment            .            setTargetFragment            (            MyParentFragment            .            this            ,            300            );            editNameDialogFragment            .            bear witness            (            fm            ,            "fragment_edit_name"            );            }            // This is called when the dialog is completed and the results have been passed                        @Override            public            void            onFinishEditDialog            (            String            inputText            )            {            Toast            .            makeText            (            this            ,            "Howdy, "            +            inputText            ,            Toast            .            LENGTH_SHORT            ).            show            ();            }            }                  

Troubleshooting

If you lot are having whatever problems, exist sure to use the checklist below:

  • In parent fragment, earlier calling dialogFragment.bear witness(), are yous calling setTargetFragment and passing in the correct fragment as the target?
  • In the dialog fragment, before calling dismiss(), are you calling listener.someCallbackMethod() on a listener casted from the getTargetFragment() passed in above?
  • Have you correctly implemented the interface and callback method fired i.east listener.someCallbackMethod() within of the parent fragment?
  • Try breakpointing each of those lines to make sure the target fragment is set property and the callback method is being executed.

With that, the two fragments are able to pass data back and forth.

Styling Dialogs

Styling Custom Dialog

Styling a DialogFragment with a custom layout works just the same as styling any views. Styling a dialog or AlertDialog requires changing several key backdrop in styles.xml such as the dialogTheme and alertDialogTheme as shown in this app here and shown below in res/values/styles.xml:

                      <!-- In res/values/colors.xml -->            <color            proper noun=            "dark_blue"            >#180065</color>            <color            proper noun=            "light_blue"            >#334ee9ff</color>            <color            name=            "medium_green"            >#3d853e</colour>            <color            proper noun=            "light_green"            >#3c2ae668</color>            <!-- In res/values/styles.xml -->            <way            name=            "AppTheme"            parent=            "Theme.AppCompat.Light"            >            <!-- Utilize default style for dialogs -->            <item            name=            "android:dialogTheme"            >@style/AppDialogTheme</item>            <!-- Apply default style for alert dialogs -->            <particular            proper noun=            "android:alertDialogTheme"            >@fashion/AppAlertTheme</item>            </manner>            <!-- Define your custom dialog theme hither extending from base -->            <mode            name=            "AppDialogTheme"            parent=            "Theme.AppCompat.Light.Dialog"            >            <!-- Define color backdrop as desired -->            <item            name=            "colorPrimary"            >@colour/dark_blue</item>            <item            proper noun=            "colorPrimaryDark"            >#000</item>            <particular            name=            "android:textColorHighlight"            >@color/light_blue</detail>            <item            proper name=            "colorAccent"            >@color/dark_blue</item>            <item            name=            "colorControlNormal"            >@color/dark_blue</item>            <!-- Define window properties as desired -->            <detail            proper noun=            "android:windowNoTitle"            >false</item>            <item            name=            "android:windowFullscreen"            >false</detail>            <particular            name=            "android:windowBackground"            >@color/medium_green</item>            <particular            name=            "android:windowIsFloating"            >true</item>            <item            proper name=            "android:windowCloseOnTouchOutside"            >true</item>            </manner>            <!-- Ascertain your custom alert theme here extending from base -->            <way            name=            "AppAlertTheme"            parent=            "Theme.AppCompat.Low-cal.Dialog.Alert"            >            <item            name=            "colorPrimary"            >@color/dark_blue</detail>            <item            name=            "colorAccent"            >@color/dark_blue</particular>            <item            name=            "colorPrimaryDark"            >#000</item>            <item            name=            "colorControlNormal"            >@color/dark_blue</particular>            <item            proper noun=            "android:textColorHighlight"            >@colour/light_blue</detail>            </way>                  

Dialog Styling Workaround

Note: There is currently a issues in the back up library that causes styles not to bear witness up properly. Changing the DialogFragment in the onCreateView to use the activity's inflater seems to resolve the issue:

                      @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Bundle            savedInstanceState            )            {            return            getActivity            ().            getLayoutInflater            ().            inflate            (            R            .            layout            .            fragment_edit_name            ,            container            );            }                  

All dialog widgets should at present be properly themed. Cheque out this stackoverflow mail service for details.

Styling Titlebar of Dialog

The titlebar can be styled using the "android:windowTitleStyle" as follows:

                      <mode            proper name=            "AppTheme"            parent=            "Theme.AppCompat.Light"            >            <!-- Apply default way for dialogs -->            <item            name=            "android:dialogTheme"            >@style/AppDialogTheme</particular>            <!-- Utilize default style for alarm dialogs -->            <particular            proper name=            "android:alertDialogTheme"            >@style/AppAlertTheme</item>            </style>            <fashion            name=            "AppDialogTheme"            parent=            "Theme.AppCompat.Light.Dialog"            >            <item            name=            "android:windowTitleStyle"            >@manner/DialogWindowTitle</item>            <!-- ...other stuff hither... -->            </style>            <style            name=            "AppAlertTheme"            parent=            "Theme.AppCompat.Light.Dialog.Alert"            >            <item            name=            "android:windowTitleStyle"            >@style/DialogWindowTitle</particular>            <!-- ...other stuff here... -->            </style>            <way            proper name=            "DialogWindowTitle"            parent=            "Base.DialogWindowTitle.AppCompat"            >            <item            proper noun=            "android:groundwork"            >@color/light_green</item>            <particular            name=            "android:gravity"            >center</particular>            <item            name=            "android:textAppearance"            >@style/DialogWindowTitleText</item>            </style>            <style            name=            "DialogWindowTitleText"            parent=            "@android:style/TextAppearance.DialogWindowTitle"            >            <particular            proper noun=            "android:textSize"            >24sp</item>            </style>                  

Removing the TitleBar from the Dialog

The TitleBar can be easily removed from your DialogFragment by overriding the onCreateDialog method:

                      @Override            public            Dialog            onCreateDialog            (            Bundle            savedInstanceState            )            {            Dialog            dialog            =            super            .            onCreateDialog            (            savedInstanceState            );            // request a window without the title                        dialog            .            getWindow            ().            requestFeature            (            Window            .            FEATURE_NO_TITLE            );            render            dialog            ;            }                  

This will give you lot a dialog box without a title bar. Read more in this StackOverflow post

Transparent Dialogs

Nosotros tin can brand the dialog (or the title of the dialog) translucent using the android:windowBackground property:

                      <style            name=            "AppDialogTheme"            parent=            "Theme.AppCompat.Light.Dialog"            >            <item            proper noun=            "android:windowIsTranslucent"            >truthful</item>            <item            name=            "android:windowBackground"            >@android:color/transparent</detail>            <!-- ...other stuff hither... -->            </way>                  

Notation that this removes the default background prototype from the dialog @drawable/abc_dialog_material_background_light and as a outcome the shadow and border is removed.

To consummate the transparent result, make sure to set the blastoff channel of the background colors as outlined here to make any groundwork colors semi-transparent.

Styling with Tertiary-Party Libraries

Notation that third party cloth libraries such every bit textile-dialogs can be used to simplify and improve dialog styling as well.

Material Dialog

In club to utilize the "material-dialogs" library, you will demand to add in maven repository to your build.gradle file. Your gradle file should wait something like this.

Sizing Dialogs

Runtime Dimensions

In sure situations, yous may desire to explicitly set the height and width of the DialogFragment at runtime during creation. This tin can be done easily with getDialog().getWindow() as follows. In the XML simply set the root layout to wrap_content with:

                      <!-- fragment_edit_name.xml -->            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:id=            "@+id/edit_name"            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            >            <!-- ...subviews here... -->            </LinearLayout>                  

In the DialogFragment java source we tin can gear up the width and tiptop onResume with:

                      public            void            onResume            ()            {            int            width            =            getResources            ().            getDimensionPixelSize            (            R            .            dimen            .            popup_width            );            int            superlative            =            getResources            ().            getDimensionPixelSize            (            R            .            dimen            .            popup_height            );            getDialog            ().            getWindow            ().            setLayout            (            width            ,            meridian            );            // Call super onResume afterward sizing                        super            .            onResume            ();            }                  

See this stackoverflow post for more information. Using this approach we could set the dialog's width as a percent of the screen within the DialogFragment with:

                      public            void            onResume            ()            {            // Store access variables for window and blank bespeak                        Window            window            =            getDialog            ().            getWindow            ();            Point            size            =            new            Point            ();            // Store dimensions of the screen in `size`                        Display            display            =            window            .            getWindowManager            ().            getDefaultDisplay            ();            display            .            getSize            (            size            );            // Fix the width of the dialog proportional to 75% of the screen width                        window            .            setLayout            ((            int            )            (            size            .            x            *            0.75            ),            WindowManager            .            LayoutParams            .            WRAP_CONTENT            );            window            .            setGravity            (            Gravity            .            Heart            );            // Call super onResume subsequently sizing                        super            .            onResume            ();            }                  

Meet this stackoverflow post for the source reference.

Sizing Adjustments for Soft Keyboard

When displaying a dialog that is accepting text input, there tin can frequently be limited space on screen considering the soft keyboard on screen eats up a lot of room. To account for this, you may want to modify the android:windowSoftInputMode property for the activity inside the AndroidManifest.xml file:

                      <!-- Configures the UI to be resized to make room for the keyboard -->            <activity            android:proper noun=            "com.example.myactivity"            android:windowSoftInputMode=            "adjustResize"            />                  

See the full details in the working with the soft keyboard guide. Alternatively, we could perform the resize directly at runtime within the onCreateView method of the fragment:

                      public            course            EditNameDialog            extends            DialogFragment            {            // ...                        @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            parent            ,            Bundle            packet            )            {            // Set to adjust screen elevation automatically, when soft keyboard appears on screen                        getDialog            ().            getWindow            ().            setSoftInputMode            (            WindowManager            .            LayoutParams            .            SOFT_INPUT_ADJUST_RESIZE            );            return            inflater            .            inflate            (            R            .            layout            .            fragment_edit_name            ,            container            );            }            }                  

See this stackoverflow mail service for additional details. Keep in mind that for either of these to work, the layout of the dialog must be configured to resize properly every bit the height changes.

Full-Screen Dialog

In other cases, nosotros want the dialog to fill the unabridged screen. Offset, in the XML layout for the dialog simply set the root layout to match_parent with:

                      <!-- fragment_edit_name.xml -->            <LinearLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            android:id=            "@+id/edit_name"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            >            <!-- ...subviews here... -->            </LinearLayout>                  

Next, within the onResume method of the DialogFragment we need to set the rules on the getDialog().getWindow() object to WindowManager.LayoutParams.MATCH_PARENT with:

                      @Override            public            void            onResume            ()            {            // Get existing layout params for the window                        ViewGroup            .            LayoutParams            params            =            getDialog            ().            getWindow            ().            getAttributes            ();            // Assign window properties to fill the parent                        params            .            width            =            WindowManager            .            LayoutParams            .            MATCH_PARENT            ;            params            .            summit            =            WindowManager            .            LayoutParams            .            MATCH_PARENT            ;            getDialog            ().            getWindow            ().            setAttributes            ((            android            .            view            .            WindowManager            .            LayoutParams            )            params            );            // Call super onResume after sizing                        super            .            onResume            ();            }                  

With this code in a higher place, the dialog may however non appear to exist entirely full-screen until we configure the background color and padding inside res/values/styles.xml with the following:

                      <style            name=            "Dialog.FullScreen"            parent=            "Theme.AppCompat.Dialog"            >            <particular            name=            "android:padding"            >0dp</item>            <item            proper noun=            "android:windowBackground"            >@android:color/white</particular>            </manner>                  

and so this style tin can be applied when creating the fragment with:

                      EditNameDialogFragment            editNameDialogFragment            =            new            EditNameDialogFragment            ();            editNameDialogFragment            .            setStyle            (            DialogFragment            .            STYLE_NORMAL            ,            R            .            style            .            Dialog_FullScreen            );            editNameDialogFragment            .            bear witness            (            getSupportFragmentManager            (),            "fragment_edit_name"            );                  

Encounter this stackoverflow post for more details. Refer to this postal service for the customized dialog styles.

Specialized Dialog Types

When using the onCreateDialog method at that place are many built-in Dialog types to take advantage of:

  • AlertDialog - Base of operations dialog that can display a message, an icon and ane-three buttons with customized text.
  • ProgressDialog - Dialog showing a progress indicator and an optional text message
  • TimePickerDialog - Dialog that allows a user to select a time.
  • DatePickerDialog - Dialog that allows a user to select a date.
  • BottomSheetDialog - Dialog that slides from the bottom.
  • Other dialogs non worth discussing here: 1 ii

Displaying a ProgressDialog

When running a long running background job, i easy fashion to notify users the app is loading is to brandish a ProgressDialog.

A ProgressDialog can exist created someday with the following:

                      ProgressDialog            pd            =            new            ProgressDialog            (            context            );            pd            .            setTitle            (            "Loading..."            );            pd            .            setMessage            (            "Delight await."            );            pd            .            setCancelable            (            imitation            );                  

The dialog can be displayed with:

                      pd            .            show            ();                  

and hidden anytime with:

                      pd            .            dismiss            ();                  

ProgressDialog can be safely paired with an AsyncTask. Refer to this ProgressDialog tutorial for a code sample. The dialog progress animation can be customized by supplying your ain animation drawable using this tutorial.

Check out the CodePath android-view-helpers library for an easier way to create simple alarm and progress modals.

Displaying Date or Fourth dimension Picker Dialogs

The native date and time pickers for Android are another example of specialized dialog fragments. Delight note that the date/fourth dimension pickers that comes with the Android SDK differ depending on the Android device version. See this section for more information.

If you wish for the containing activity to receive the date or time selected past the dialog, you should ensure that the Activity implements the respective interface. If nosotros want the date picker to be shown from within another dialog fragment, refer to setting a target fragment. For instance, for a date picker fragment, you will want to ensure that the activity implements the OnDateSetListener interface:

                      import            java.util.Calendar            ;            // do not import java.icu.utils.Calendar                        public            class            DatePickerFragment            extends            DialogFragment            {            @Override            public            Dialog            onCreateDialog            (            Bundle            savedInstanceState            )            {            // Utilize the current time as the default values for the picker                        final            Calendar            c            =            Calendar            .            getInstance            ();            int            twelvemonth            =            c            .            get            (            Calendar            .            YEAR            );            int            month            =            c            .            get            (            Agenda            .            Calendar month            );            int            twenty-four hours            =            c            .            become            (            Calendar            .            DAY_OF_MONTH            );            // Activeness needs to implement this interface                        DatePickerDialog            .            OnDateSetListener            listener            =            (            DatePickerDialog            .            OnDateSetListener            )            getActivity            ();            // Create a new example of TimePickerDialog and return information technology                        return            new            DatePickerDialog            (            getActivity            (),            listener            ,            year            ,            month            ,            day            );            }                  

The Activity, which likewise is responsible for instantiating this dialog fragment, but needs to implement the onDateSet method of this interface.

                      public            grade            MyActivity            extends            AppCompatActivity            implements            DatePickerDialog            .            OnDateSetListener            {            // attach to an onclick handler to evidence the date picker                        public            void            showDatePickerDialog            (            View            5            )            {            DatePickerFragment            newFragment            =            new            DatePickerFragment            ();            newFragment            .            show            (            getSupportFragmentManager            (),            "datePicker"            );            }            // handle the engagement selected                        @Override            public            void            onDateSet            (            DatePicker            view            ,            int            yr            ,            int            monthOfYear            ,            int            dayOfMonth            )            {            // store the values selected into a Calendar case                        final            Agenda            c            =            Calendar            .            getInstance            ();            c            .            gear up            (            Calendar            .            YEAR            ,            year            );            c            .            set            (            Calendar            .            MONTH            ,            monthOfYear            );            c            .            set            (            Calendar            .            DAY_OF_MONTH            ,            dayOfMonth            );            }                  

A similar approach can be washed with the time picker too:

                      public            class            TimePickerFragment            extends            DialogFragment            {            @Override            public            Dialog            onCreateDialog            (            Bundle            savedInstanceState            )            {            // Use the current time equally the default values for the picker                        final            Calendar            c            =            Calendar            .            getInstance            ();            int            hour            =            c            .            get            (            Calendar            .            HOUR_OF_DAY            );            int            infinitesimal            =            c            .            become            (            Calendar            .            Minute            );            // Activity has to implement this interface                        TimePickerDialog            .            OnTimeSetListener            listener            =            (            TimePickerDialog            .            OnTimeSetListener            )            getActivity            ();            // Create a new example of TimePickerDialog and render it                        return            new            TimePickerDialog            (            getActivity            (),            listener            ,            60 minutes            ,            infinitesimal            ,            DateFormat            .            is24HourFormat            (            getActivity            ()));            }            public            void            onTimeSet            (            TimePicker            view            ,            int            hourOfDay            ,            int            infinitesimal            )            {            // Do something with the time called by the user                        }            }                  

Modal Bottom Sheets

With the support design library, information technology as well fairly easy to convert your dialog to use modal bottom sheets. Instead of DialogFragment, y'all can extend from BottomSheetDialogFragment:

                      public            form            MyBottomSheetDialogFragment            extends            BottomSheetDialogFragment            {            @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Bundle            savedInstanceState            )            {            return            inflater            .            inflate            (            R            .            layout            .            fragment_bottom_sheet            ,            container            );            }            }                  

When you show this fragment, you lot will notice that it appears from the bottom:

                      MyBottomSheetDialogFragment            myDialog            =            new            MyBottomSheetDialogFragment            ();            FragmentManager            fm            =            getSupportFragmentManager            ();            myDialog            .            bear witness            (            fm            ,            "test"            );                  

Things To Annotation

  • Notice that we are using the back up library version of fragments for meliorate compatibility in our code samples. The non-support version works identically.
  • Dialogs are just classes that extend DialogFragment and define the view to display in the floating content area.
  • DialogFragment classes must define an empty constructor as shown in the code samples, otherwise the Android system will raise an exception when it attempts to instantiate the fragment.
  • After loading the initial view, the action immediately shows the dialog using the show() method which allows the fragment manager to keep track of the state and gives us sure things for free such every bit the back button dismissing the fragment.
  • In the lawmaking snippets to a higher place, notice the utilize of requestFocus and input modes to control the advent of the soft keyboard when the dialog appears.
  • Nosotros can dismiss a dialog one of 2 ways. Here nosotros are calling dismiss() within the Dialog grade itself. Information technology could also be chosen from the Action like the show() method. In API 13, removeDialog(int id) and dismissDialog(int id) were deprecated. dismiss() directly on the dialog is at present the recommended approach every bit outlined here.

References

  • http://android-developers.blogspot.com/2012/05/using-dialogfragments.html
  • http://codebaum.wordpress.com/2013/04/10/dialog-fragments/
  • http://developer.android.com/reference/android/app/DialogFragment.html
  • http://www.coderzheaven.com/2013/02/fourteen/dialogfragments-android-unproblematic-instance/
  • http://stackoverflow.com/questions/12912181/simplest-aye-no-dialog-fragment

smithwheink73.blogspot.com

Source: https://guides.codepath.com/android/using-dialogfragment

0 Response to "Android Studio Alert Dialog Dont Show Again"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel