Press and hold

3 replies [Last post]
lukeambrogio
User offline. Last seen 14 weeks 6 days ago. Offline
Joined: 5 Jul 2011

I'm trying to find a neat way to create and event when a user presses and holds for a couple of seconds on a UI object, which is different from just tapping.

I was thinking of creating an on touch event and creating a timer on the "began" phase and cancel the timer on the "ended" and "cancelled" events. The timer increments a counter value. For each call by that object to the handler which is not "began", "cancelled", or "ended" (not sure what to do with the "move" event) I check if the counter is greater than say 2 (meaning 2 seconds) and perform the action and cancel the timer.

Is this a good strategy or are there simpler way?

Thanks

Replies

Satheesh's picture
Satheesh
User offline. Last seen 5 hours 14 min ago. Offline
Joined: 25 May 2011

You can do something like this.

1
2
3
4
5
6
7
8
9
local startTime
local function onTouch(event)
        if event.phase == "began" then 
                startTime = event.time
        elseif event.phase == "ended" then 
                timeElapsed = event.time - startTime
        end
end
Runtime:addEventListener("touch",onTouch)

lukeambrogio
User offline. Last seen 14 weeks 6 days ago. Offline
Joined: 5 Jul 2011

I did something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
local holdCount = 0
local holdTimer = nil
local eventTarget = nil
 
local function holdCountListener(event)
        holdCount = holdCount + 1
        if holdCount > 0 then
                --do something with eventTarget
                timer.cancel( holdTimer )
        end
end
        
local function onTap(event)             
        if "began" == event.phase then
                holdTimer = timer.performWithDelay(1000, holdCountListener, 0)
                holdCount = 0
                eventTarget = event
        end
        elseif "ended" == event.phase then 
                timer.cancel( holdTimer )
                if holdCount > 0 then
                        --do somethig with eventTarget
                        timer.cancel( holdTimer )
                else
                        --do something else with eventTarget
                end
        elseif "cancelled" == event.phase then
                timer.cancel( holdTimer )               
        end
end

It works but I don't like it...

lukeambrogio
User offline. Last seen 14 weeks 6 days ago. Offline
Joined: 5 Jul 2011

I'll try this too...

Viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.