Search code examples
android-layoutandroid-studioontouchlistener

onTouchListener not working after layout change


I want to get feedback when the user swipes anywhere on the screen. I found some code that does that using an onTouchListener. And it worked. Today I did some rework on my UI setup and added a lot of new layouts to organize it a little nicer. But my onTouch event is never triggering any more!

My guess is that some of the layouts might be overlapping and stealing the event. But I have not been successful trying to use the following arguments in the xml.

android:clickable="false"
android:focusable="false"
android:touchscreenBlocksFocus="false"
android:visibility="invisible"

This is the code running in onCreate:

View window = getWindow().getDecorView();
window.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        System.out.println("YEY! A TOUCH EVENT!");
        return true;
    }
});

RelativeLayout tab1 = (RelativeLayout) findViewById(R.id.layTab1);
tab1.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        System.out.println("YEY! A TOUCH EVENT!");
        return true;
    }
});

Any ideas as for what might have changed when adding new layouts is greatly appriciated!


Solution

  • I finally figured out what the problem was after much troubleshooting. My layout hierchy was the following:

    - activity_main (RelativeLayout)
    --- layTab1 (RelativeLayout)
    ----- (ScrollView)
    ------- layTab1View (LinearLayout)
    --------- (STUFF FOR THIS TAB)
    --- layTab2 (RelativeLayout)
    ----- (ScrollView)
    ------- layTab2View (LinearLayout)
    --------- (STUFF FOR THIS TAB)
    

    And I was trying to grab events from the activity_main layout. Which was working fine til I added a ScrollView. Apparently, the ScrollView consumes all the touch events. To work around this problem. I had to add a listener to all of the LinearLayout children of the ScrollView since only one tab will be active at the time.

    I do how ever feel that having multiple different elements listen for the same event to trigger a menu popup is slightly unnessesary? So if at all possibly I would love to hear suggestions as for how I could solve this more "cleanly".