dmSherazi
dmSherazi

Reputation: 3831

hide a relative layout when user clicks outside it, Android

I have an activity with two relative layouts. In one of them I have three buttons and it width is set to wrap_content. I want to be bale to hide this layout when the user clicks on any area that is outside this layout.

How can I do this

Upvotes: 0

Views: 1157

Answers (1)

nstosic
nstosic

Reputation: 2614

Use the OnTouchEvent() inside your activity:

@Override
public boolean onTouchEvent(MotionEvent event) {
    float touchPointX = event.getX();
    float touchPointY = event.getY();
    int[] coordinates = new int[2];
    layoutToHide.getLocationOnScreen(coordinates);
    if(touchPointX < coordinates[0] || touchPointX > coordinates[0] + layoutToHide.getWidth() || touchPointY < coordinates[1] || touchPointY > coordinates[1] + layoutToHide.getHeight())
    layoutToHide.setVisibility(View.INVISIBLE) // or View.GONE if you want more space.

P.S. I haven't tested this code and be sure to know the difference between View.INVISIBLE and View.GONE so you can figure out which one is the appropriate choice for you.

Upvotes: 3

Related Questions