MinusReputation MinusReputation - 1 year ago 96
Android Question

Trouble with Fragment Alert Box

I am currently attempting to build a simple settings Fragment alert box.

I've built the main body of the alert box, however I've noticed that the actual Dialog method is not used. Also, this Dialog method replaced the


How do I actually use the Dialog method? I can't seem to simply call it after I create the Dialog method because it comes up as an error.

Do I have to reference it in some XML?
If so, then which XML - the Fragment's XML or its parent Activity's XML?

The following is the code of my Dialog Fragment. I have not modified its XML as of yet.

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

public class ExceedingLimitFragment extends Fragment {

public Dialog onCreateDialogExceed (Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.exceeding_limit_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent ExceedingLimitPositiveIntent = new Intent (ExceedingLimitFragment.this.getActivity(), SettingsMenu.class);
builder.setNegativeButton(R.string.exceeding_limit_negative, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {

return builder.create();


Answer Source

I am noticing some issues with the above code. Fist:

public Dialog onCreateDialogExceed (Bundle savedInstanceState) {

seems wrong. You should only be calling the super method of the method you are overriding. In this case onCreateDialogExceed is your very own method so you should be calling onCreate() to that. The system relies in you calling those methods right after overriding them, so that it knows they have been called in the right order.

Does ExceedingLimitFragment need to display a DialogFragment or is it in fact the DialogFragment? If the answer is the later, make sure to extend that class instead of Fragment. After you do that, rename onCreateDialogExceed() to onCreateDialog(), which is going to be called by the system when the dialog actually needs to be created.

In order to display the dialog fragment you need a reference to that from your Activity or fragment and do something like:

new ExceedingLimitFragment().show(getFragmentManager(), TAG);

as in @dev.bmax 's answer

As for your title, finish() is a method of Activity. Neither Fragments or DialogFragments know about it, so it makes sense for your IDE to complain about it. In order to use it inside fragments make sure to do

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download