Android: Close dialog window on touch

2019-01-23 06:18发布

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 the dialog, but it doesnt exist.

How would this be possible?

5条回答
爷的心禁止访问
2楼-- · 2019-01-23 06:24

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.

查看更多
ら.Afraid
3楼-- · 2019-01-23 06:25
Dialog dialog = new Dialog(context)
{
    public boolean dispatchTouchEvent(MotionEvent event)  
    {
        dialog.dismiss();
        return false;
    }
};

And you are done!

查看更多
小情绪 Triste *
4楼-- · 2019-01-23 06:31

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();

        }
查看更多
来,给爷笑一个
5楼-- · 2019-01-23 06:35

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

查看更多
beautiful°
6楼-- · 2019-01-23 06:43

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();
查看更多
登录 后发表回答