Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with alertdialog show in fragment android

I have followed android example but I have an incomprehensive error :

void showDialog() {
    DialogFragment newFragment = MyAlertDialogFragment.newInstance();
    newFragment.show(fm, "alert");
}

public static class MyAlertDialogFragment extends DialogFragment {
    public static MyAlertDialogFragment newInstance() {
        MyAlertDialogFragment frag = new MyAlertDialogFragment();
        return frag;
    }

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity()).setTitle("test")
                .setMessage("bla bla bla").create();
    }
}

newFragment.show(fm, "alert"); returns me an error :

The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)

Someone could help me ?

like image 681
user831602 Avatar asked Jul 06 '11 12:07

user831602


People also ask

Is AlertDialog deprecated?

A simple dialog containing an DatePicker . This class was deprecated in API level 26.

How do you show DialogFragment?

Showing the DialogFragment It is not necessary to manually create a FragmentTransaction to display your DialogFragment . Instead, use the show() method to display your dialog. You can pass a reference to a FragmentManager and a String to use as a FragmentTransaction tag.

Is DialogFragment deprecated?

This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.


3 Answers

The problem is because you need to be using the support package's FragmentManager but you are using the native FragmentManager when you call getFragmentManager(). Try calling getSupportFragmentManager() when initializing your variable fm.

like image 89
Jacob Phillips Avatar answered Oct 22 '22 00:10

Jacob Phillips


Actually after you do as @Jacob says, you also have to make sure that you include DialogFragment from the Support package and not from the native package.

You can do that by importing,

import android.support.v4.app.DialogFragment;
like image 35
Tobio Avatar answered Oct 22 '22 01:10

Tobio


In my case my minSDK is set to 14 so I did not want to use the support package. My problem was I was importing the wrong DialogFragment like so:

import android.support.v4.app.DialogFragment;

I changed it to this and it worked:

import android.app.DialogFragment;
like image 31
Ryan R Avatar answered Oct 21 '22 23:10

Ryan R