1. 程式人生 > >Android 自定義View實現拖拽效果

Android 自定義View實現拖拽效果

騰訊QQ有那種紅點拖動效果,今天就來實現一個簡單的自定義View拖動效果,再回到原處,並非完全仿QQ紅點拖動

先來看一下效果圖

簡單說一下實現步驟

1.建立一個類繼承View

2.繪製出一個小球

3.重寫onTouchEvent,來根據手指放下,移動,擡起,來控制小球

4.直接在佈局中引用

先貼一張圖看下View的座標系

下面就貼一下程式碼,最後會給出原始碼

public class CustomView extends View {

    private int lastX;
    private int lastY;
    private int startLeft;
    private int startRight;
    private int startTop;
    private int startBottom;

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //畫一個小球
        Paint paint = new Paint();
        paint.setStrokeWidth(30);
        paint.setColor(Color.parseColor("#FF0000"));
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        canvas.drawCircle(getWidth()/2,getHeight()/2,30,paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        //獲取手機觸控的座標
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (action){
            case MotionEvent.ACTION_DOWN://按下,獲取小球初始的位置
                startLeft = getLeft();
                startRight = getRight();
                startTop = getTop();
                startBottom = getBottom();
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_MOVE://移動,小球跟隨手指的移動
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                layout(getLeft()+offsetX,getTop()+offsetY,
                        getRight()+offsetX,getBottom()+offsetY);
                break;
            case MotionEvent.ACTION_UP://當手指擡起時,回到小球初始的位置
                layout(startLeft, startTop, startRight, startBottom);
                break;
        }
        return true;
    }
}

直接在佈局中引用該自定義View就可以,寬高給固定