Search code examples
buttonluascrollviewcoronasdkdisplayobject

lua corona - how to disable touch events widget.newScrollView


I have a widget.newScrollView component and a widget.newButton in front of it. Unfortunately when i click my button it also calls my ScrollView "tap" handler. How do i stop my ScrollView from getting this event? Here is some of the code I'm using:

local function handleButtonEvent( event )
    if ( "ended" == event.phase ) then
        print( "Button was pressed and released" )
    end
    return true; **I tried this - but it had no effect**
end

added

local button1 = widget.newButton(
{
    label = "button",
    onEvent = handleButtonEvent,
    emboss = false,
    shape = "roundedRect",
    width = 400,
    height = 100,
    cornerRadius = 32,
    fillColor = { default={1,0,0,1}, over={1,0.1,0.7,1} },
    strokeColor = { default={1,0.4,0,1}, over={0.8,0.8,1,1} },
    strokeWidth = 4,
    fontSize=100;
}

I've got an array (planets) of display.NewImages and my handler - like this:

local planets = {};
planets[1] = display.newImage( "planetHexs/001.png", _topLeft_x, _topLeft_y);
planets[2] = display.newImage( "planetHexs/002.png", _topLeft_x, _topLeft_y + _planet_height2 );
....

local scrollView = widget.newScrollView(
{
    top = 0,
    left = 0,
    width = display.actualContentWidth,
    height = display.actualContentHeight,
    scrollWidth = 0,
    scrollHeight = 0,
    backgroundColor = { 0, 0, 0, 0.5},
    verticalScrollDisabled=true;
}

for i = 1, #planets do
    local k = planets[i];
    scrollView:insert( k )
end

function PlanetTapped( num )
    print( "You touched the object!"..num );
end

for i = 1, #planets do
    local k = planets[i];
    k:addEventListener( "tap", function() PlanetTapped(i) end )
end

I get this print log:

Button was pressed and released

You touched the object2

Solution

  • You must return true on your event functions to prevent propagation. This essentially tells Corona that the event was handled correctly and that no more event listeners for that event should be fired. You can read more about event propagation here in the docs.

    "tap" and "touch" events are handled with different listeners, so if you wish to stop taps when you touch the button, you will have add a "tap" listener to your button as well, that essentially just returns true to prevent, or block tap events to anything behind it.

    button1:addEventListener("tap", function() return true end)
    

    Since the button does not have a tap event, tap events simply go through the button, to any objects behind it which do have a "tap" event.