Tap outside Android dialog to dismiss it?

前端 未结 12 1373
梦如初夏
梦如初夏 2020-12-07 18:44

I was wondering if it\'s possible to somehow tap outside a popup dialog (or an Activity with a dialog theme), and dismiss it by just tapping outside of it?

I made a

相关标签:
12条回答
  • 2020-12-07 19:23

    You could use Activity#setFinishOnTouchOutside too, if your dialog is an Activity. That's gotta be the shortest way for Activitys ;)

    (It's API 11+ though. But API <= 10 is generally screen size normal.)

    0 讨论(0)
  • 2020-12-07 19:24
        dialog = new Dialog(MainActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_layout);
        dialog.getWindow().setBackgroundDrawableResource(
                android.R.color.transparent);
        dialog.setCancelable(false);
    
        dialog.setCanceledOnTouchOutside(true);
    

    Check if you have this line of code or not....

        dialog.setCanceledOnTouchOutside(true);
    
    0 讨论(0)
  • 2020-12-07 19:24

    Simply I write dialog.setCanceledOnTouchOutside(false); and it work for me, window will not dismiss on outside tap .

    0 讨论(0)
  • 2020-12-07 19:26

    this.setFinishOnTouchOutside(false);

    you can use this

    0 讨论(0)
  • 2020-12-07 19:28

    You may use

      dialog.setCancelable(true\false); 
    

    For the lastest vesrions of Android;

    It will disable outSideTouching event.

    0 讨论(0)
  • 2020-12-07 19:29

    My app is a single activity with Theme.Holo.Dialog. In my case the other answer did not work. It only made the other background apps or the launch screen to receive touch events.

    I found that using dispatchTouchEvent works in my case. I think it is also a simpler solution. Here's some sample code on how to use it to detect taps outside the activity with a Dialog theme:

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Rect dialogBounds = new Rect();
        getWindow().getDecorView().getHitRect(dialogBounds);
    
        if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
            // Tapped outside so we finish the activity
            this.finish();
        }
        return super.dispatchTouchEvent(ev);
    }
    
    0 讨论(0)
提交回复
热议问题