Android拖拽圖片效果的實現其實也很簡單,只要對需要拖拽的圖片設置一個TouchListener即可,在Listener的方法裡邊對圖片的位置進行計算更改就可以達到效果了。具體實現如下:
1.Activity
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.View.OnTouchListener;
- import android.widget.ImageView;
- publicclass DragPicActivity extends Activity {
- private ImageView imageView;
- @Override
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.drag);
- imageView = (ImageView) findViewById(R.id.drag_pic);
- imageView.setOnTouchListener(new OnTouchListener() {
- privatefloat x, y;
- privateint mx, my;
- @Override
- publicboolean onTouch(View v, MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- x = event.getX();
- y = event.getY();
- case MotionEvent.ACTION_MOVE:
- mx = (int) (event.getRawX() - x);
- //減去的50是title和status bar的高度
- my = (int) (event.getRawY() - y - 50);
- v.layout(mx, my, mx + v.getWidth(), my + v.getHeight());
- break;
- }
- returntrue;
- }
- });
- }
- }
2.layout
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center"
- android:orientation="vertical">
- <ImageView
- android:id="@+id/drag_pic"
- android:layout_width="50dip"
- android:layout_height="50dip"
- android:src="@drawable/ic_launcher"/>
- </LinearLayout>
這樣拖拽圖片的效果就出來了,同樣的拖拽其他控件應該也是一樣的做法,沒測試,但拖拽圖片其實就是拖拽ImageView嘛,so easy是吧!
相關閱讀:Android中實現圖片的拖拽 http://www.linuxidc.com/Linux/2012-01/50980.htm