在触摸事件的Android移动视图 [英] Android move view on touch event
问题描述
我想移动两种不同的观点为我的布局,这样的用户可以显示它喜欢他的愿望。
I would like to move two different views into my layout, so that an user can display it like his wishes.
到目前为止,我已经做了如下code来处理触摸事件:
So far I've made the following code to handle the touch event:
this.viewEvent.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event)
{
final int y = (int) event.getRawY();
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
element.setEventY(y - params.topMargin);
break;
case MotionEvent.ACTION_UP:
viewGroup.invalidate();
break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
params.topMargin = y - element.getEventY();
params.bottomMargin = screenHeight - view.getHeight() - params.topMargin;
// Avoid out of screen
if (params.topMargin < 0) return true;
// Apply changes
view.setLayoutParams(params);
break;
}
return true;
}
});
元素
是一个自定义对象来处理的位置的一个实例。
screenHeight
是由显示给定屏幕高度
类。
element
is an instance of a custom object to handle the position.
screenHeight
is the screen height given by the Display
class.
我能够移动元素,但和它的闪烁,当我抚摸它,一旦我把我的手指了,认为只是disapear。我甚至无法找回它,它只是在屏幕中。
I'm able to move the element but it's blinking when I touch it and once I put my finger up, the view just disapear. I can't even retrieve it, it's just out of the screen.
我都做什么了吗?
感谢您的帮助
推荐答案
使用下面的code进行简单的按移动
:
USe the following code to perform a simple Touch to move
:
layout_counter.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event)
{
if (currentState != State.EDIT_MOVE) return false;
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();
if (view.getId() != R.id.layout_counter) return false;
switch (event.getAction())
{
case MotionEvent.ACTION_MOVE:
params.topMargin = (int) event.getRawY() - view.getHeight();
params.leftMargin = (int) event.getRawX() - (view.getWidth() / 2);
view.setLayoutParams(params);
break;
case MotionEvent.ACTION_UP:
params.topMargin = (int) event.getRawY() - view.getHeight();
params.leftMargin = (int) event.getRawX() - (view.getWidth() / 2);
view.setLayoutParams(params);
break;
case MotionEvent.ACTION_DOWN:
view.setLayoutParams(params);
break;
}
return true;
}
});
其中, layout_counter
是要移动的观点。
不要忘记把你的运动元素融入到一个的FrameLayout
Don't forget to put your movable elements into a FrameLayout
这篇关于在触摸事件的Android移动视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!