Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
Goofyahead Avatar asked May 07 '12 10:05

Goofyahead


2 Answers

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..!!

like image 87
Rookie Avatar answered Nov 08 '22 18:11

Rookie


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.

like image 36
user1208720 Avatar answered Nov 08 '22 19:11

user1208720