I\'d like to close a dialog window in my android app by simply touching the screen.. is this possible? If so, how?
I\'ve looked into setting some \"onClickEven\" on
You can extend Dialog
class and override dispatchTouchEvent()
method.
EDIT: Also you can implement Window.Callback
interface and set it as dialog's window callback using dialog.getWindow().setCallback()
. This implementation should call corresponding dialog's methods or handle events in its own way.
Dialog dialog = new Dialog(context)
{
public boolean dispatchTouchEvent(MotionEvent event)
{
dialog.dismiss();
return false;
}
};
And you are done!
You can use dialog.setCanceledOnTouchOutside(true);
which will close the dialog if you touch u=outside the dialog.
If someone still searching for a solution to dismiss a Dialog by onTouch Event, here is a snippet of code:
public void onClick(View v) {
AlertDialog dialog = new AlertDialog(MyActivity.this){
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
dismiss();
return false;
}
};
dialog.setIcon(R.drawable.MyIcon);
dialog.setTitle("MyTitle");
dialog.setMessage("MyMessage");
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
If your dialog contains any view try to get the touch events in that view and dismiss your dialog when user touch on that view. For example if your dialog has any Image then your code should be like this.
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.mylayout);
//create a layout with imageview
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();