1. 程式人生 > >實現拖動圖片

實現拖動圖片

action_main

<wanghuiqi.bawie.com.whq_dalls.MyDragPicture
        android:id="@+id/pic"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/a"
        />

MyDragPicture

package wanghuiqi.bawie.com.whq_dalls;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

@SuppressLint("AppCompatCustomView")
public class MyDragPicture extends ImageView {

    private int mDownX;
    private int mDownY;

    public MyDragPicture(Context context) {
        super(context);
    }

    public MyDragPicture(Context context,  AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //獲取手指處的橫座標和縱座標
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN://手指按下
                mDownX = x;
                mDownY = y;
                break;
            case MotionEvent.ACTION_MOVE://手指移動
                //計算移動的距離
                int moveX = x - mDownX;
                int moveY = y - mDownY;
                //呼叫layout方法重新放置它的位置
                movingXY(moveX,moveY);

                break;
            case MotionEvent.ACTION_UP:
                break;
        }

        return true;
    }
    private void movingXY(int moveX, int moveY) {
        //移動View
        layout(getLeft()+moveX,getTop()+moveY,getRight()
                +moveX,getBottom()+moveY);
    }
}