Android用户点击外部时隐藏相对布局

时间:2013-11-14 08:25:01

标签: android android-layout

我有两个相对布局的活动。在其中一个中我有三个按钮,宽度设置为wrap_content。当用户点击此布局之外的任何区域时,我想要隐藏此布局。

我该怎么做

1 个答案:

答案 0 :(得分:3)

在您的活动中使用OnTouchEvent():

@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。我没有测试过此代码,请务必了解View.INVISIBLEView.GONE之间的区别,以便您可以找出适合您的选择。

相关问题