Weird Nerd Weird Nerd - 14 days ago 7
Android Question

How to detect the button click in Activity from the Alert Dialog present in a Fragment?

I am having a DialogFragment like this,

public class Dfragment extends DialogFragment {

public Dfragment() {
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
ab.setMessage("Delete Everything").setTitle("DELETE DB")
.setPositiveButton("OK",new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
}
})

.setNegativeButton("CANCEL",new DialogInterface.OnClickListener()

{ @Override
public void onClick(DialogInterface dialog, int which) { }
});


return ab.create();
}

}


I can detect the positive/negative from within the Fragment, but how do I detect it from an Activity from where it had been called.

Here is the code implemented in the Activity,

Dfragment frag = new Dfragment();
frag.show(getFragmentManager(),"THISDIALOG");


So in the Activity how do I determine which button has been clicked ?

Things I tried so far,

From the above Fragment code,

setPositiveButton("OK",null) replaced in the above code but still did not work.

What code will I need to modify to make it work as desired ?

EDIT 1:

I know it can be achieved by interfaces but I would like to do it without that.

Answer

I have one suggetion for you. You can do like:

public abstract class Dfragment extends DialogFragment {

    public Dfragment() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
        ab.setMessage("Delete Everything").setTitle("DELETE DB")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onPositiveButtonClick();
                    }
                })

                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener()

                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onNegativeButtonClick();
                    }

                });


        return ab.create();
    }

    public abstract void onPositiveButtonClick();

    public abstract void onNegativeButtonClick();

}

And Create object

Dfragment frag = new Dfragment() {
    @Override
    public void onPositiveButtonClick() {

    }

    @Override
    public void onNegativeButtonClick() {

    }
};
frag.show(getFragmentManager(),"THISDIALOG");
Comments