Goofyahead
Goofyahead

Reputation: 5884

Dismiss DialogFragment onClick

I was trying to make a DialogFragment that could be dismissed when tapped, after some search i decided to go with this implementation:

public class ErrorDialogFragment extends RoboDialogFragment {

private static final String MESSAGE_ARG = "message";
private TextView text;

public ErrorDialogFragment newInstance (String message){
    ErrorDialogFragment f = new ErrorDialogFragment();

        Bundle args = new Bundle();
        args.putString(MESSAGE_ARG, message);
        f.setArguments(args);

        return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
    View v = inflater.inflate(R.layout.error_dialog_fragment, container, false);
    v.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ErrorDialogFragment.this.dismiss();
        }
    });

    text = (TextView) v.findViewById(R.id.error_dialog_text_textView);
    text.setText(getArguments().getString(MESSAGE_ARG));
    return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_TITLE, 0);
}

The alert dialog can have a custom message and will be dismissed when tapped.

Do you think is a better way to achieve this?

Thanks.

Upvotes: 10

Views: 16576

Answers (3)

Jorge Casariego
Jorge Casariego

Reputation: 22212

I'm calling a DialogFragment from an Activity. After click a button in the dialog I'm using an interface to call a method inside the activity. In that activity I'm executing this:

// This is the code inside the activity that call the dialog
Fragment fragment = getSupportFragmentManager().findFragmentByTag("MyDialog");
if(fragment != null) {
    DialogFragment dialog = (DialogFragment) fragment;
    dialog.dismiss();
}

Upvotes: 1

Rookie
Rookie

Reputation: 8790

You can use dialog.setCanceledOnTouchOutside(true); which will close the dialog if you touch outside the dialog. or

Try this tutorial http://iserveandroid.blogspot.com/2010/11/how-to-dismiss-custom-dialog-based-on.html . Hope it Helps..!!

Upvotes: 14

user1208720
user1208720

Reputation: 515

final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(msg);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int which) 
            {
                alertDialog.dismiss();
            }
        });
        alertDialog.setIcon(R.drawable.error_icon);
        alertDialog.show();

just use this code whenever you want to show the alert, and its ok onclick event the dialog box will dismiss.

Upvotes: 1

Related Questions