Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Click-through of Android ImageVIew?

I have an ImageView overlay inside of a RelativeLayout and want to prevent any clicks from going through the ImageView to the Buttons etc that are behind it (thus in effect disabling the entire RelativeLayout).

Is the a simpler way of doing this then iterating the RelativeLayout views and setting them to disabled as I currently am doing using this code:

RelativeLayout rlTest = (RelativeLayout ) findViewById(R.id.rlTest);
for (int i = 0; i < rlTest.getChildCount(); i++) {
       View view = rlTest.getChildAt(i);
       view.setEnabled(true);
}
like image 823
Apqu Avatar asked Apr 15 '14 09:04

Apqu


4 Answers

you can set the image to be

android:clickable="true"
like image 198
Kirill Kulakov Avatar answered Nov 17 '22 23:11

Kirill Kulakov


Simply call rlTest.setClickable(false). This will prevent the click to be propagate to the children

like image 29
Blackbelt Avatar answered Nov 17 '22 23:11

Blackbelt


There is a much cleaner way

You can use:

android:onClick="preventClicks"

in XML and in your Activity

public void preventClicks(View view) {}

This works with fragments. Example inside this Activity has multiple fragments overlapping one another, just by adding the XML attribute in the background of your fragment it will still call the Activity.preventClicks and will prevent touches on fragments behind it

like image 31
Markos Evlogimenos Avatar answered Nov 17 '22 22:11

Markos Evlogimenos


The following solution works in the general case:

_container.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // NOTE: This prevents the touches from propagating through the view and incorrectly invoking the button behind it
        return true;
    }
});

It basically blocks any touches from propagating through the view by marking the touch event as handled. This works on both UI controls and layout containers (ie: LinearLayout, FrameLayout etc.).

The solution to set "clickable" as false did not work for me for layout containers either in code or in the view XML.

like image 35
Marchy Avatar answered Nov 18 '22 00:11

Marchy