Android: Close dialog window on touch

前端 未结 5 1615
时光取名叫无心
时光取名叫无心 2020-12-15 09:25

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

相关标签:
5条回答
  • 2020-12-15 09:39

    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.

    0 讨论(0)
  • 2020-12-15 09:47
    Dialog dialog = new Dialog(context)
    {
        public boolean dispatchTouchEvent(MotionEvent event)  
        {
            dialog.dismiss();
            return false;
        }
    };
    

    And you are done!

    0 讨论(0)
  • 2020-12-15 09:48

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

    0 讨论(0)
  • 2020-12-15 09:48

    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();
    
            }
    
    0 讨论(0)
  • 2020-12-15 09:58

    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();
    
    0 讨论(0)
提交回复
热议问题