Long-Press to get Context-Sensitive Modal Menu?
Anyone have sample code that shows how to handle a long-press of a Table View item under Android?
i.e. gives a modal context-sensitive menu when you hold-down a TableView item - many apps on Android do this.
3 Answers
-
Accepted Answer
The best way I've been able to simulate a long press on a table view is by the following:
var touched = false; tableview.addEventListener('click', function(e) { touched = false; }); tableview.addEventListener('touchstart', function(e){ touched = true; setTimeout(function(){ if (touched) alert("Long press"); },1000); }); tableview.addEventListener('touchmove', function(e){ touched = false; }); tableview.addEventListener('touchend', function(e){ touched = false; });
Instead of an alert you can use Titanium.UI.OptionDialog to display options.
-
Thanks for this code! I am currently using a modified version of this:
var longTap = false; var timeOut = null; obj.addEventListener('touchstart', function(e) { longTap = false; timeOut = setTimeout(function() { longTap = true; }, 200); }); obj.addEventListener('touchmove', function(e) { longTap = false; }); obj.addEventListener('touchend', function(e) { clearTimeout(timeOut); if (longTap) { longTap = false; // do something } else { // do what you would do in 'click' event } });
-
Thanks for the tip Kristof! Here's a variation that I worked for a slider control(though it's useful for other objects as well):
var longTap = false; slider.addEventListener('touchstart', function(e) { longTap = false; setTimeout(function() { if (longTap) { longTap = false; // do something } }, 1000); }); slider.addEventListener('touchmove', function(e) { longTap = false; }); slider.addEventListener('touchend', function(e) { longTap = false; });
The difference here is that if you move the slider thumb to a given spot, then pause for a second, it'll trigger the 'longTap' (as opposed to waiting until you reach 'touchend'). I used this in a video-based app to 'zoom in' on a section of the video clip.