Android: Close dialog window on touch

允我心安 提交于 2019-12-18 02:42:48

问题


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?


回答1:


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




回答2:


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



回答3:


Dialog dialog = new Dialog(context)
{
    public boolean dispatchTouchEvent(MotionEvent event)  
    {
        dialog.dismiss();
        return false;
    }
};

And you are done!




回答4:


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.




回答5:


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

        }


来源:https://stackoverflow.com/questions/5801634/android-close-dialog-window-on-touch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!