Ashwin Shirva
Ashwin Shirva

Reputation: 1451

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 :)

Upvotes: 3

Views: 1734

Answers (1)

bricklore
bricklore

Reputation: 4165

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)

Upvotes: 1

Related Questions