android View with View.GONE still receives onTouch

2019-01-21 16:01发布

This is confusing me:

As far as I have read, a view with setVisibility(View.GONE); should not receive any more touch- or click events. My layout has two parts, which will be visible or gone so that only one of them is visible and usable at a time but View.GONE doesn't do the trick. I can't see the GONE view, as expected, but it still reacts to onClick (and consumes the event the other view should get).

Can you help me?

Maybe of interest: When I start my project one view is GONE, the other visible. This time it will work as expected (the GONE view is basically ignored), but after setting View.GONE through the code it'll stop working.

9条回答
你好瞎i
2楼-- · 2019-01-21 16:11

try adding .clearAnimation() in the onAnimationEnd override.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-21 16:22

What I expect is happening is that you make a view invisible, but that views children still respond to clicks (ie your view is a ViewGroup). You could do something along the lines of:

private void hideTheChildren(View v){
    if(v instanceof ViewGroup) {
        int count = ((ViewGroup)v).getChildCount();
        for(int k = 0 ; k < count ; k++) {
            hideTheChildren(((ViewGroup)v).getChildAt(k));
        }
        v.setVisibility(View.GONE);
    }
    else {
        v.setClickable(false);
        v.setVisibility(View.GONE);
    }
}

of course then you also have to do the opposite

private void showTheChildren(View v){
    if(v instanceof ViewGroup) {
        int count = ((ViewGroup)v).getChildCount();
        for(int k = 0 ; k < count ; k++) {
            showTheChildren(((ViewGroup)v).getChildAt(k));
        }
        v.setVisibility(View.VISIBLE);
    }
    else {
        v.setClickable(true);
        v.setVisibility(View.VISIBLE);
    }
}

This has worked for me in the past. I don't currently know of a better way to do this.

查看更多
forever°为你锁心
4楼-- · 2019-01-21 16:25

Do you maybe use animations to show/hide the views? I get this behaviour when I use animations that have android:fillEnabled="true" android:fillAfter="true" Don't understand it, and seems like a bug - if I use animations without fillEnabled/fillAfter, all works as expected...

查看更多
登录 后发表回答