Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a touch event outside the activity border

I have activity A over activity B. Activity A does not fill the entire screen.(Its not dialog activity though)I want to close activity A when the touch event is detected outside the activity A border. how to detect a touch event outside the activity border?

@Override

public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
        Toast.makeText(getApplicationContext(), "Hi", 3000).show();

        return true;
    }

    return false;
}

This code doesn't work as it works only for dialog activities. Please help..Thanks in advance :)

like image 333
Ashwin Shirva Avatar asked Nov 28 '25 14:11

Ashwin Shirva


1 Answers

i dont know if this works, so please test it :)
but it should be pretty easy:

in actvity A's onCreate():

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    //set us to non-modal, so that others can receive the outside touch events.
    getWindow().setFlags(LayoutParams.FLAG_NOT_TOUCH_MODAL, LayoutParams.FLAG_NOT_TOUCH_MODAL);

    //and watch for outside touch events too
    getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

    //be sure to set the content view after setting those flags!!
    setContentView(R.layout.my_view);
}

now you receive touch events in normal `onTouch()'
just check there if it's outside (get x and y and check against your window's position)

like image 195
bricklore Avatar answered Nov 30 '25 02:11

bricklore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!