我是一名 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()
没有正确地工作,请建议我应该怎么做,以便按钮可以轻松移动到鼠标或手势触摸的位置?