Search code examples
androidandroid-alertdialog

How to pass a onclick event into a method to dismiss dialog after completion in Android


Trying to create a generic function to do custom dialog box, running into an issue with dismissing the dialog box from itself, here is my code in the activity. I am trying to finish the dialog but not the activity. I also can't reference the alertDialog to do .dismiss() from the calling class. Any ideas? Yes I can technically have a showPopupMessage for every time I want to show this popup and do the onclick inside of it easily. I am trying to make a generic app wide one where I just set the onclicklistener outside the method and pass it in.

 case R.id.deleteText:
                            final Context context = this;
                            View.OnClickListener rightEvent = new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteCard(btCardToken);
                                    finish();
                                }
                            };
                            showPopupMessage(context,"Company", "Are you sure you wish to delete this card?", "CANCEL", "YES", rightEvent);
                            break;

Then my code in my generic class,

public void showPopupMessage(Context context, String header, String message, String leftButtonText, String rightButtonText, View.OnClickListener rightEvent)
{
    LayoutInflater inflator = LayoutInflater.from(context);
    View promptsView = inflator.inflate(R.layout.edit_text_prompt, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final StyledTextView alertHeader = (StyledTextView)promptsView.findViewById(R.id.alertHeader);
    final StyledTextView alertText = (StyledTextView)promptsView.findViewById(R.id.alertText);
    final StyledTextView rightButton = (StyledTextView)promptsView.findViewById(R.id.rightButton);
    final StyledTextView leftButton = (StyledTextView)promptsView.findViewById(R.id.leftButton);
    final EditText inputEditTextBox = (EditText)promptsView.findViewById(R.id.inputEditTextBox);

    alertHeader.setText(header);
    alertText.setText(message);
    inputEditTextBox.setVisibility(View.GONE);
    leftButton.setText(leftButtonText);
    rightButton.setText(rightButtonText);

    // set dialog message
    alertDialogBuilder.setCancelable(true);

    // create alert dialog
    final AlertDialog alertDialog = alertDialogBuilder.create();
    leftButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            alertDialog.dismiss();
        }
    });
    rightButton.setOnClickListener(rightEvent);
    alertDialog.show();
}

Solution

  • You should create a dialog by extending DialogFragment and creating a AlertDialog in the onCreateDialog() callback method. To deliver the dialog clicks, define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog.

    Your dialog could look something like this:

    public class MyDialog extends DialogFragment {
    
        // Use this instance of the interface to deliver action events
        MyDialogListener mListener;
    
        // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            // Verify that the host activity implements the callback interface
            try {
                // Instantiate the MyDialogListener so we can send events to the host
                mListener = (MyDialogListener) activity;
            } catch (ClassCastException e) {
                // The activity doesn't implement the interface, throw exception
                throw new ClassCastException(activity.toString() + " must implement MyDialogListener");
            }
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Build the dialog and set up the button click handlers
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            // Get the layout inflater
            LayoutInflater inflater = getActivity().getLayoutInflater();
            builder.setView(inflater.inflate(R.layout.edit_text_prompt, null))
            // Inflate and set the layout for the dialog
            // Pass null as the parent view because its going in the dialog layout
            final StyledTextView alertHeader = (StyledTextView) promptsView.findViewById(R.id.alertHeader);
            final StyledTextView alertText = (StyledTextView) promptsView.findViewById(R.id.alertText);
            final StyledTextView rightButton = (StyledTextView) promptsView.findViewById(R.id.rightButton);
            final StyledTextView leftButton = (StyledTextView) promptsView.findViewById(R.id.leftButton);
            final EditText inputEditTextBox = (EditText) promptsView.findViewById(R.id.inputEditTextBox);
    
            alertHeader.setText(header);
            alertText.setText(message);
            inputEditTextBox.setVisibility(View.GONE);
            leftButton.setText(leftButtonText);
            rightButton.setText(rightButtonText);
    
            // set dialog message
            builder.setCancelable(true);
            leftButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onLeftClicked(MyDialog.this);
                }
            });
            rightButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onRightClicked(MyDialog.this);
                }
            });
            return builder.create();
        }
    
        /* The activity that creates an instance of this dialog fragment must
         * implement this interface in order to receive event callbacks.
         * Each method passes the DialogFragment in case the host needs to query it. */
        public interface MyDialogListener {
            public void onLeftClicked(DialogFragment dialog);
            public void onRightClicked(DialogFragment dialog);
        }
    }
    

    In your activity, call the dialog and respond to the button clicks like so,

    public class MainActivity extends FragmentActivity
                              implements MyDialog.MyDialogListener{
        ...
    
        public void showMyDialog() {
            // Create an instance of the dialog fragment and show it
            DialogFragment dialog = new MyDialog();
            dialog.show(getSupportFragmentManager(), "MyDialog");
        }
    
        // The dialog fragment receives a reference to this Activity through the
        // Fragment.onAttach() callback, which it uses to call the following methods
        // defined by the MyDialog.MyDialogListener interface
        @Override
        public void OnLeftClicked(DialogFragment dialog) {
            // User touched the dialog's left button
            ...
        }
    
        @Override
        public void onRightClicked(DialogFragment dialog) {
            // User touched the dialog's right button
            ...
        }
    }
    

    For more info you can check the official docs: http://developer.android.com/guide/topics/ui/dialogs.html