Android Studio Alert Dialog Dont Show Again

Overview

DialogFragment is a specialized Fragment used when you desire to display an overlay modal window within an activity that floats on summit of the rest 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 some other Activity.

DialogFragment is now the canonical fashion to display overlays; using Dialog directly is considered bad practice.

Usage

The minimum that must be implemented when creating a DialogFragment is either the onCreateView method or the onCreateDialog method. Employ onCreateView when the entire view of the dialog is going to exist defined via custom XML. Apply onCreateDialog when you but need to construct and configure a standard Dialog class (such as AlertDialog) to display.

Note: The unabridged guide below requires every fragment related class imported to utilise the androidx.fragment.app namespace and not the android.app namespace. If any imported course (FragmentManager, DialogFragment, etc) uses the android.app namespace, compile-fourth dimension errors will occur.

Custom View

Let's starting time by providing the code for creating a completely custom dialog based on an XML view. First, an example 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=            "center"            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 support version of dialog fragment:

                      import            androidx.fragment.app.DialogFragment            ;            // ...                        public            class            EditNameDialogFragment            extends            DialogFragment            {            private            EditText            mEditText            ;            public            EditNameDialogFragment            ()            {            // Empty constructor is required for DialogFragment                        // Make sure not to add arguments to the constructor                        // Use `newInstance` instead equally shown below                        }            public            static            EditNameDialogFragment            newInstance            (            String            title            )            {            EditNameDialogFragment            frag            =            new            EditNameDialogFragment            ();            Parcel            args            =            new            Packet            ();            args            .            putString            (            "title"            ,            championship            );            frag            .            setArguments            (            args            );            render            frag            ;            }            @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            container            ,            Bundle            savedInstanceState            )            {            return            inflater            .            inflate            (            R            .            layout            .            fragment_edit_name            ,            container            );            }            @Override            public            void            onViewCreated            (            View            view            ,            @Nullable            Parcel            savedInstanceState            )            {            super            .            onViewCreated            (            view            ,            savedInstanceState            );            // Get field from view                        mEditText            =            (            EditText            )            view            .            findViewById            (            R            .            id            .            txt_your_name            );            // Fetch arguments from bundle and set title                        Cord            championship            =            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 Activity extending AppCompatActivity:

                      // Note: `FragmentActivity` works hither likewise                        public            class            DialogDemoActivity            extends            AppCompatActivity            {            @Override            public            void            onCreate            (            Packet            savedInstanceState            )            {            super            .            onCreate            (            savedInstanceState            );            setContentView            (            R            .            layout            .            master            );            showEditDialog            ();            }            individual            void            showEditDialog            ()            {            FragmentManager            fm            =            getSupportFragmentManager            ();            EditNameDialogFragment            editNameDialogFragment            =            EditNameDialogFragment            .            newInstance            (            "Some Title"            );            editNameDialogFragment            .            prove            (            fm            ,            "fragment_edit_name"            );            }            }                  

For this to piece of work properly brand sure that all the fragment related items (FragmentDialog) are from the androidx.fragment.app namespace.

Build Dialog

2d, let'due south take a look at how to build a dialog but by customizing the bachelor Dialog objects that we tin construct. For more than details about the unlike types of dialogs, cheque out the "Things to Annotation" section beneath.

                      class            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"            ,            title            );            frag            .            setArguments            (            args            );            render            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 y'all 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            !=            null            &&            dialog            .            isShowing            ())            {            dialog            .            dismiss            ();            }            }            });            return            alertDialogBuilder            .            create            ();            }            }                  

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

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

Passing Information to Activeness

To pass information from a dialog to an Activeness, use the same arroyo you would employ for whatsoever fragment which is creating a custom listener. In brusk, you lot will demand to do the following:

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

This example below demonstrates how to pass a data result back to the action when the "Done" push button is pressed on the keyboard but this works similarly for other cases or for the AlertDialog (simply utilize the listeners divers for each of the buttons):

                      public            class            EditNameDialogFragment            extends            DialogFragment            implements            OnEditorActionListener            {            private            EditText            mEditText            ;            // ane. Defines the listener interface with a method passing dorsum data result.                        public            interface            EditNameDialogListener            {            void            onFinishEditDialog            (            String            inputText            );            }            // ...                        @Override            public            void            onViewCreated            (            View            view            ,            @Nullable            Parcel            savedInstanceState            )            {            // ...                        // two. Setup a callback when the "Washed" button is pressed on keyboard                        mEditText            .            setOnEditorActionListener            (            this            );            }            // Fires whenever the textfield has an activeness 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            ());            // Shut the dialog and render back to the parent action                        dismiss            ();            return            true            ;            }            return            simulated            ;            }            }                  

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

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

Note: setOnEditorActionListener used above to dismiss requires the employ of the soft keyboard in the emulator which tin exist enabled through AVD or past testing on a device. If you don't desire to enable soft keyboard, you lot may desire 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 within the context of another fragment. For example, a screen has tabs with a form contained in a fragment. The form has an input for selecting dates using a date picker in a dialog. In this instance, we may want to pass the date back not to the activity just instead to the parent fragment. This data can be passed back straight to the parent fragment:

                      import            androidx.fragment.app.DialogFragment            ;            public            course            EditNameDialogFragment            extends            DialogFragment            {            // Defines the listener interface                        public            interface            EditNameDialogListener            {            void            onFinishEditDialog            (            Cord            inputText            );            }            // Call this method to send the data back to the parent fragment                        public            void            sendBackResult            ()            {            // Notice the apply of `getTargetFragment` which volition exist ready when the dialog is displayed                        EditNameDialogListener            listener            =            (            EditNameDialogListener            )            getTargetFragment            ();            listener            .            onFinishEditDialog            (            mEditText            .            getText            ().            toString            ());            dismiss            ();            }            }                  

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

                      import            androidx.fragment.app.Fragment            ;            public            class            MyParentFragment            extends            Fragment            implements            EditNameDialogListener            {            // Phone call this method to launch the edit dialog                        private            void            showEditDialog            ()            {            FragmentManager            fm            =            getFragmentManager            ();            EditNameDialogFragment            editNameDialogFragment            =            EditNameDialog            .            newInstance            (            "Some Championship"            );            // SETS the target fragment for use later when sending results                        editNameDialogFragment            .            setTargetFragment            (            MyParentFragment            .            this            ,            300            );            editNameDialogFragment            .            show            (            fm            ,            "fragment_edit_name"            );            }            // This is called when the dialog is completed and the results accept been passed                        @Override            public            void            onFinishEditDialog            (            String            inputText            )            {            Toast            .            makeText            (            this            ,            "How-do-you-do, "            +            inputText            ,            Toast            .            LENGTH_SHORT            ).            show            ();            }            }                  

Troubleshooting

If you are having any issues, be sure to use the checklist below:

  • In parent fragment, earlier calling dialogFragment.show(), are you 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.e listener.someCallbackMethod() inside of the parent fragment?
  • Try breakpointing each of those lines to make sure the target fragment is fix property and the callback method is being executed.

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

Styling Dialogs

Styling Custom Dialog

Styling a DialogFragment with a custom layout works only the same every bit styling whatever views. Styling a dialog or AlertDialog requires irresolute several key properties in styles.xml such equally the dialogTheme and alertDialogTheme every bit shown in this app here and shown beneath in res/values/styles.xml:

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

Dialog Styling Workaround

Note: There is currently a bug in the back up library that causes styles not to prove up properly. Irresolute the DialogFragment in the onCreateView to utilize 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. Check out this stackoverflow post for details.

Styling Titlebar of Dialog

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

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

Removing the TitleBar from the Dialog

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

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

This will give y'all a dialog box without a title bar. Read more than in this StackOverflow post

Transparent Dialogs

We can make the dialog (or the championship of the dialog) translucent using the android:windowBackground holding:

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

Note that this removes the default background image from the dialog @drawable/abc_dialog_material_background_light and as a event the shadow and border is removed.

To complete the transparent effect, make sure to prepare the alpha channel of the background colors as outlined here to make whatever background colors semi-transparent.

Styling with Tertiary-Party Libraries

Annotation that third party material libraries such every bit textile-dialogs can exist used to simplify and improve dialog styling as well.

Material Dialog

In club to use the "cloth-dialogs" library, you volition need to add in maven repository to your build.gradle file. Your gradle file should look something similar this.

Sizing Dialogs

Runtime Dimensions

In sure situations, you may want to explicitly set the height and width of the DialogFragment at runtime during creation. This can be done easily with getDialog().getWindow() as follows. In the XML simply prepare 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 coffee source we can set the width and superlative onResume with:

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

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

                      public            void            onResume            ()            {            // Store access variables for window and blank point                        Window            window            =            getDialog            ().            getWindow            ();            Indicate            size            =            new            Point            ();            // Store dimensions of the screen in `size`                        Display            display            =            window            .            getWindowManager            ().            getDefaultDisplay            ();            display            .            getSize            (            size            );            // Set 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            .            Centre            );            // Telephone call super onResume after sizing                        super            .            onResume            ();            }                  

Meet this stackoverflow mail for the source reference.

Sizing Adjustments for Soft Keyboard

When displaying a dialog that is accepting text input, there can often be express space on screen because the soft keyboard on screen eats upwardly a lot of room. To business relationship 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 brand room for the keyboard -->            <activity            android:name=            "com.example.myactivity"            android:windowSoftInputMode=            "adjustResize"            />                  

Meet 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            class            EditNameDialog            extends            DialogFragment            {            // ...                        @Override            public            View            onCreateView            (            LayoutInflater            inflater            ,            ViewGroup            parent            ,            Bundle            package            )            {            // Set to conform screen summit 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            );            }            }                  

Come across this stackoverflow post for boosted details. Keep in mind that for either of these to work, the layout of the dialog must be configured to resize properly as the height changes.

Total-Screen Dialog

In other cases, we want the dialog to fill the unabridged screen. Commencement, 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 hither... -->            </LinearLayout>                  

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

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

With this lawmaking higher up, the dialog may even so not appear to be entirely full-screen until we configure the background color and padding inside res/values/styles.xml with the post-obit:

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

and and then this fashion tin can be practical when creating the fragment with:

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

See this stackoverflow post for more than details. Refer to this post for the customized dialog styles.

Specialized Dialog Types

When using the onCreateDialog method there are many congenital-in Dialog types to take advantage of:

  • AlertDialog - Base dialog that can display a message, an icon and 1-iii 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 appointment.
  • BottomSheetDialog - Dialog that slides from the bottom.
  • Other dialogs non worth discussing here: 1 2

Displaying a ProgressDialog

When running a long running groundwork task, one easy style to notify users the app is loading is to brandish a ProgressDialog.

A ProgressDialog can exist created someday with the post-obit:

                      ProgressDialog            pd            =            new            ProgressDialog            (            context            );            pd            .            setTitle            (            "Loading..."            );            pd            .            setMessage            (            "Please expect."            );            pd            .            setCancelable            (            faux            );                  

The dialog tin can be displayed with:

                      pd            .            show            ();                  

and subconscious 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 tin exist customized by supplying your own animation drawable using this tutorial.

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

Displaying Date or Time Picker Dialogs

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

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

                      import            java.util.Calendar            ;            // do non import java.icu.utils.Calendar                        public            class            DatePickerFragment            extends            DialogFragment            {            @Override            public            Dialog            onCreateDialog            (            Bundle            savedInstanceState            )            {            // Use the current fourth dimension as the default values for the picker                        final            Agenda            c            =            Calendar            .            getInstance            ();            int            year            =            c            .            become            (            Calendar            .            Twelvemonth            );            int            month            =            c            .            become            (            Calendar            .            Calendar month            );            int            day            =            c            .            get            (            Calendar            .            DAY_OF_MONTH            );            // Action needs to implement this interface                        DatePickerDialog            .            OnDateSetListener            listener            =            (            DatePickerDialog            .            OnDateSetListener            )            getActivity            ();            // Create a new instance of TimePickerDialog and render information technology                        return            new            DatePickerDialog            (            getActivity            (),            listener            ,            year            ,            month            ,            day            );            }                  

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

                      public            class            MyActivity            extends            AppCompatActivity            implements            DatePickerDialog            .            OnDateSetListener            {            // attach to an onclick handler to show the date picker                        public            void            showDatePickerDialog            (            View            five            )            {            DatePickerFragment            newFragment            =            new            DatePickerFragment            ();            newFragment            .            show            (            getSupportFragmentManager            (),            "datePicker"            );            }            // handle the date selected                        @Override            public            void            onDateSet            (            DatePicker            view            ,            int            year            ,            int            monthOfYear            ,            int            dayOfMonth            )            {            // shop the values selected into a Calendar instance                        final            Agenda            c            =            Agenda            .            getInstance            ();            c            .            set            (            Calendar            .            Twelvemonth            ,            year            );            c            .            set            (            Calendar            .            MONTH            ,            monthOfYear            );            c            .            fix            (            Calendar            .            DAY_OF_MONTH            ,            dayOfMonth            );            }                  

A similar arroyo can be done with the time picker too:

                      public            class            TimePickerFragment            extends            DialogFragment            {            @Override            public            Dialog            onCreateDialog            (            Bundle            savedInstanceState            )            {            // Use the current time every bit the default values for the picker                        terminal            Calendar            c            =            Calendar            .            getInstance            ();            int            hour            =            c            .            go            (            Calendar            .            HOUR_OF_DAY            );            int            minute            =            c            .            go            (            Calendar            .            MINUTE            );            // Activity has to implement this interface                        TimePickerDialog            .            OnTimeSetListener            listener            =            (            TimePickerDialog            .            OnTimeSetListener            )            getActivity            ();            // Create a new instance of TimePickerDialog and render it                        render            new            TimePickerDialog            (            getActivity            (),            listener            ,            hour            ,            minute            ,            DateFormat            .            is24HourFormat            (            getActivity            ()));            }            public            void            onTimeSet            (            TimePicker            view            ,            int            hourOfDay            ,            int            minute            )            {            // Do something with the time chosen by the user                        }            }                  

Modal Bottom Sheets

With the support design library, information technology also adequately easy to convert your dialog to employ modal lesser sheets. Instead of DialogFragment, you can extend from BottomSheetDialogFragment:

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

When you bear witness this fragment, yous will find that it appears from the lesser:

                      MyBottomSheetDialogFragment            myDialog            =            new            MyBottomSheetDialogFragment            ();            FragmentManager            fm            =            getSupportFragmentManager            ();            myDialog            .            show            (            fm            ,            "examination"            );                  

Things To Note

  • Notice that we are using the support library version of fragments for better 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 organisation volition raise an exception when it attempts to instantiate the fragment.
  • After loading the initial view, the activity immediately shows the dialog using the show() method which allows the fragment manager to go on track of the land and gives u.s. certain things for free such as the back button dismissing the fragment.
  • In the code snippets above, discover the utilise of requestFocus and input modes to command the appearance of the soft keyboard when the dialog appears.
  • We can dismiss a dialog one of two ways. Here we are calling dismiss() within the Dialog class itself. It could as well be called from the Activity similar the show() method. In API 13, removeDialog(int id) and dismissDialog(int id) were deprecated. dismiss() straight on the dialog is now the recommended approach as outlined here.

References

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

lansfordbity1954.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel