Touch + Hold

Hi all,

Sorry maybe this questions was posted before but I don’t where is search in new forum :frowning:

My question:

I have project required user to touch a picture for 2 seconds then the listener function run.

Should I use timer or touch with phase event?

I don’t have clear scenario … and really I don’t know how to do that?

Thank you in advanced.
[import]uid: 100448 topic_id: 27797 reply_id: 327797[/import]

Hi

you would use both the event phases and a timer. roughly:

on phase /begin/, start a timer which will run your callback function in 2 seconds. (whatever you need to do - dispatch an event, add/remove UI elements ,etc). you’ll probably want to set focus on the touch event to make sure your handler will get the phase end.

on phase /end/, cancel the timer if it still exists. this covers the case when the user releases the touch before 2 seconds is up.

cheers,
dmc
[import]uid: 74908 topic_id: 27797 reply_id: 112599[/import]

Thank you for quick reply.

Here is my code:

[lua]local object = display.newImage( “p3.png” )

function object:touch( event )

local timerHand
local function listener( event )
print( “listener called” )
end

if event.phase == “began” then
print(“began”);
timerHand = timer.performWithDelay( 2000, listener )

elseif event.phase == “ended” or event.phase == “cancelled” then
print(“ended”);
timer.cancel( timerHand )
end
return true
end
object:addEventListener( “touch”, object )[/lua]

But how can I cancel timer if user does not hold for 2 seconds?
Even when I put timer cancel in ended event the timer still working!!

Best Regards,
iOS
[import]uid: 100448 topic_id: 27797 reply_id: 112665[/import]

Hello iOs,

I changed your code up a little…:slight_smile: hopefully it is what your looking for…

Try this and see if you can make this work for ya:

Or just play with it…maybe to fit your needs… :wink:

Didn’t mean to hijack your post …tho…just trying to help…

local object = display.newImage( "p3.png" );  
   
function object:touch( event )  
  
 local timerHand;  
  
 local function listener( event )  
  
 print( "listener called" );  
  
 if timerHand ~= nil then  
  
 timer.cancel( timerHand );  
  
 print( "TimerHand CANCELLED" );  
  
 end  
 end  
  
 if event.phase == "began" then  
  
 print( "began phase" );  
  
 display.getCurrentStage():setFocus( event.target );  
  
 timerHand = timer.performWithDelay( 2000, listener );  
  
 print( "BEGAN: timerHand: ", timerHand );  
  
 elseif event.phase == "ended" or event.phase == "cancelled" then  
  
 print( "ENDED: timerHand: ", timerHand );  
  
 print( "ended / cancelled phase" );  
  
 display.getCurrentStage():setFocus( nil );  
  
 if timerHand ~= nil then  
  
 print( "timerHand NOT = nil" );  
  
 timer.cancel( timerHand );  
  
 end  
 end  
  
 return true;  
  
end  
  
object:addEventListener( "touch", object );  

Fingers crossed :wink:

Best Regards,

Larry
[import]uid: 107633 topic_id: 27797 reply_id: 112670[/import]