Manitoba Manitoba - 1 month ago 6
Android Question

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.

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;
}
});


element
is an instance of a custom object to handle the position.
screenHeight
is the screen height given by the
Display
class.

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.

Did I make something wrong ?

Thanks for your help

Answer

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;
        }
    });

Where layout_counter is the view you want to move.

Don't forget to put your movable elements into a FrameLayout

Comments