Can you get the message in a DialogFragment and return the message as a string back to an activity?

139 Views Asked by At

Basically I have created a DialogFragment that contains 3 buttons and a message. The message is and integer value starting at 0 and the positive and negative buttons allow the user to increment and decrement the value in the message by 1 each time the button is clicked. once the user clicks the neutral button "Ok" I want to know is it possible to get the message as a string and return it back to the main activity? If not how is it possible to do this?

I know how to pass data between a fragment and activity i just want to know is it possible to get the message in a fragment and store it to a string variable

Many thanks

p.s sorry if i'm using this wrong its my first time here

public class AddEmployeesDialogFragment extends DialogFragment {

    //variables
    int value = 0;
    AlertDialog.Builder builder;
    AlertDialog alertDialog;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        builder = new AlertDialog.Builder(getActivity());

        builder.setTitle("How many Employees do you want to add to");
        builder.setMessage((new Integer(value)).toString());
        builder.setPositiveButton("+", null);
        builder.setNegativeButton("---", null);
        builder.setNeutralButton("Ok", null);

        // Create the AlertDialog object and return it
        return builder.create();
    }

    @Override
    public void onStart(){
        super.onStart();
        alertDialog = (AlertDialog)getDialog();
        if(alertDialog != null)
        {
            Button positiveButton = (Button)alertDialog.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    value++;
                    alertDialog.setMessage((new Integer(value)).toString());
                }
            });
            Button negativeButton = (Button)alertDialog.getButton(Dialog.BUTTON_NEGATIVE);
            negativeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(value > 0) {
                        value--;
                    }
                    alertDialog.setMessage((new Integer(value)).toString());
                }
            });
            Button neutralButton = (Button)alertDialog.getButton(Dialog.BUTTON_NEUTRAL);
            neutralButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }
}

0

There are 0 best solutions below