How To Make Drag & Drop Button In Android

- 1 answer

I want to make a drag and drop button. Drag it where you want it to do and it stays there. Below code only scales the button, doesn't change its position.

package com.dynamic;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.dynamic.R;
import com.dynamic.R.layout;

public class dy extends Activity {
     int status;
     private FrameLayout layout;
     ImageView image;
     Button b;
     LayoutParams params;
     public void onCreate(Bundle savedInstanceState) {
            final Button tv=(Button)findViewById(;

            layout = (FrameLayout) findViewById(;
            params = new LayoutParams(100,100);

            params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            tv.setOnTouchListener(new View.OnTouchListener(){

        public boolean onTouch(View v, MotionEvent me) {
            // TODO Auto-generated method stub

            if (me.getAction() == MotionEvent.ACTION_DOWN) {
                status = 0;

            if (me.getAction() == MotionEvent.ACTION_UP) {
                status = 1;
                //Log.i("Drag", "Stopped Dragging");
            } else if (me.getAction() == MotionEvent.ACTION_MOVE) {
                if (status == 0) {

                    tv.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);
                //  b.setPadding(0,50,0,0);

            return false;



I am working on something similar to this. Here is the OnTouchListener that I am using:

         myOnTouchListener = new OnTouchListener() {
         public boolean onTouch(View v, MotionEvent me){
             if (me.getAction() == MotionEvent.ACTION_DOWN){
                 oldXvalue = me.getX();
                 oldYvalue = me.getY();
                 Log.i(myTag, "Action Down " + oldXvalue + "," + oldYvalue);
             }else if (me.getAction() == MotionEvent.ACTION_MOVE  ){
                LayoutParams params = new LayoutParams(v.getWidth(), v.getHeight(),(int)(me.getRawX() - (v.getWidth() / 2)), (int)(me.getRawY() - (v.getHeight())));
             return true;

v is the view that you are wanting to move, in your case it you'd replace v with your button. Also note that in order to get this to work I had to use an AbsoluteLayout as the parent view in my xml file. I know that it is deprecated but it seemed more logical to use that then a RelativeLayout and trying to set the margins dynamically to move the view around. The formula that I used for the new x and y positions tries to make it so that the view is centered on your finger while you are moving it. But its not quite perfect, depending on the size of the view it will still be a little off center from your finger.