拖拽图片效果的实现其实也很简单,只要对需要拖拽的图片设置一个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;
- public class DragPicActivity extends Activity {
- private ImageView p_w_picpathView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.drag);
- p_w_picpathView = (ImageView) findViewById(R.id.drag_pic);
- p_w_picpathView.setOnTouchListener(new OnTouchListener() {
- private float x, y;
- private int mx, my;
- @Override
- public boolean 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;
- }
- return true;
- }
- });
- }
- }
2.layout
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns: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>