Search code examples
javaandroidandroid-preferencesandroid-dialogfragment

DialogFragment in Class that extends from AppCompatPreferenceActivity


my issue is that I have my preference activity that extends from AppCompatPreferenceActivity and I need to show a DialogFragment. So when I do the following:

DialogFragmente dialogFragment= new MyDialogFragmentClass()
DialogFragment.show(getSupportFragmentManager(),"My Dialog")

I get an error because I can not use the getSupportFragmentManager() method. So my question is how can I use that method if my class extends from AppCompatPreferenceActivity.

I tried using getFragmentManager() instead but it is not working neither.

this are my classes:

public class Settings_acticity extends AppCompatPreferenceActivity {
    private SwitchPreference banner_switch;
    private SharedPreferences sharedPreferences;
    private ListPreference interstial_ad;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        DialogFragment dialogFragment = new MyDialog();
        dialogFragment.show(getSupportFragmentManager(), "My dialog");
    }
 }

And the DialogFragment class:

public class MyDialog extends DialogFragment {


    public MyDialog(){
        // Required empty public constructor
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View vista=getActivity().getLayoutInflater().inflate(R.layout.fragment_MyDialog,null);
        setCancelable(false);

        builder.setView(vista).setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //Yes Code
            }
        }).setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            //No code
            }
        });
        return builder.create();
    }

}

Thanks for the help!


Solution

  • This is probably because you use DialogFragment from Support Library.

    Try using the original one by importing android.app.DialogFragment instead of android.support.v4.app.DialogFragment

    Then you can show the dialog with:

    MyDialog myDialog = new MyDialog();
    myDialog.show(getFragmentManager(), "My Dialog");