Android拖放按钮



我在android中工作,我使用的是一个按钮。现在我想执行这个按钮的拖放操作。

这是我的main.xml

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/ll_first"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
>
 <Button  
   android:id="@+id/btn"
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
    android:text="drag me"
  />
 </LinearLayout>

这是我在鼠标拖动时移动这个按钮的代码:-

public class DragdropActivity extends Activity implements OnTouchListener {
private final static int START_DRAGGING = 0;
private final static int STOP_DRAGGING = 1;
private Button btn;
private int status;
private ImageView image;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn = (Button) findViewById(R.id.btn);
    btn.setDrawingCacheEnabled(true);
    btn.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent me) {
    if (me.getAction() == MotionEvent.ACTION_DOWN) {
        status = START_DRAGGING;

    }
    if (me.getAction() == MotionEvent.ACTION_UP) {
        status = STOP_DRAGGING;
        Log.i("Drag", "Stopped Dragging");
    } else if (me.getAction() == MotionEvent.ACTION_MOVE) {
        if (status == START_DRAGGING) {
            System.out.println("Dragging");
            Log.v("***Drag and drop **",
                    "me.getRawX and Y = " + me.getRawX() + " "
                            + me.getRawY());
            Log.v("***Drag and drop **",
                    "image position = " + image.getLeft() + " "
                            + image.getRight());
     btn.setPadding((int) me.getRawX(), (int) me.getRawY(), 0,0); //this is not working fine. 

            btn.invalidate();
        }
    }
    return false;
}

}

我认为btn.setPadding()工作不正常,请建议我该怎么做,以便按钮可以轻松移动到鼠标或手势触摸的位置?

我这样解决了我的问题。

    @Override
     public boolean onTouch(View view, MotionEvent me) {
    if (me.getAction() == MotionEvent.ACTION_DOWN) {
        status = START_DRAGGING;

    }
    if (me.getAction() == MotionEvent.ACTION_UP) {
        status = STOP_DRAGGING;
        Log.i("Drag", "Stopped Dragging");
    } else if (me.getAction() == MotionEvent.ACTION_MOVE) {
        if (status == START_DRAGGING) {
            System.out.println("Dragging");
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    50, 50);
            layoutParams.setMargins((int) me.getRawX() - 25,
                    (int) me.getRawY() - 50, 0, 0);
            layout.removeView(btn);
            layout.addView(btn, layoutParams);
            btn.invalidate();
        }
    }
    return false;
}

现在一切正常。

您应该获得按钮的布局参数,设置左、右、上、下,并将这些布局参数设置回按钮

尝试从onTouch()方法返回true。也许会成功的。在我的一个应用程序中,它的工作原理是return false没有按照我的触摸移动视图,但return true语句解决了这个问题。

最新更新