Freely Draggable TextView – Fine Control Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Freely Draggable TextView – Fine Control without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a TextView with the id “tx”. I’ve set an OnTouchListener to allow the user to drag the view.

tx.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        float x = event.getRawX();
        float y = event.getRawY();
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            // Offsets center the TextView to the center of the MotionEvent
            view.setX(x - view.getWidth() / 2);
            view.setY(y - view.getHeight() / 2);
        }

        return true;
    }

How can I create a dragging effect whereby wherever the user initially clicks, that position is the one where the dragging begins? I want fine control (identical to Snapchat or Autodesk Sketch) so if I decide to drag from the left, there is no re-centering. I think this is what most users expect from this kind of interaction. They don’t want their TextView to be re-positioned at the center of where they first clicked.

All help greatly appreciated!

Answer

There will always be an MotionEvent.ACTION_DOWN preceded by MotionEvent.ACTION_MOVE

You should first handle the MotionEvent.ACTION_DOWN event which will give you the position where the user first touched. You can store those coordinates and then use them in the MotionEvent.ACTION_DOWN to do whatever you want to do.

We are here to answer your question about Freely Draggable TextView – Fine Control - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji