codecookie.net
Titanium Drag Problems
Today I retried to get into Android programming with Appcelerator Titanium.
I wanted to have an object which I can drag around on the screen. Easy going. I thought... My first try was simple and easy:
var circleSize = 100;
var circle = Titanium.UI.createView({
height:circleSize,
width:circleSize,
anchorPoint:{x:(circleSize/2),y:(circleSize/2)},
borderRadius:(circleSize/2),
backgroundColor:'#00ff00'
});
circle.addEventListener('touchmove', function(e) {
circle.setTop(e.y);
circle.setLeft(e.x);
});
The result: The circle jumps randomly around.. Not nice..
After some trys i found solution with a satisfying appearance.
You have to create two equal object and set the touchevent on the one but move the other one. I know ugly and confusing. But who cares.
var circleSize = 100;
var circle = Titanium.UI.createView({
height:circleSize,
width:circleSize,
anchorPoint:{x:(circleSize/2),y:(circleSize/2)},
borderRadius:(circleSize/2),
backgroundColor:'#00ff00'
});
var circle2 = Titanium.UI.createView({
height:circleSize,
width:circleSize,
anchorPoint:{x:(circleSize/2),y:(circleSize/2)},
borderRadius:(circleSize/2),
backgroundColor:'#ff0000',
top:10
});
circle2.addEventListener('touchstart', function(e) {
circle.setVisible(true);
circle2.setVisible(false);
});
circle2.addEventListener('touchmove', function(e) {
circle.setTop(e.y + circleY - (circleSize/2));
circle.setLeft(e.x + circleX - (circleSize/2));
});
circle2.addEventListener('touchcancel', function(e) { moveend(e); });
circle2.addEventListener('touchend', function(e) { moveend(e); });
function moveend(e) {
circleY = circle.getTop();
circleX = circle.getLeft();
circle2.setTop(circle.getTop());
circle2.setLeft(circle.getLeft());
circle.setVisible(false);
circle2.setVisible(true);
}
Have a smooth drag.