Android 實現滑動的幾種方法(一)onLayout方法 和 offsetLeftAndRight()與offsetTopAndBottom();

onLayout方法:

package com.example.administrator.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Administrator on 2015/11/22 0022.
 */
public class MyView extends View {
    int lastX ;
    int lastY ;
    public MyView(Context context) {
        super(context);
    }

    public MyView(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:
                lastX = x;
                lastY = y;
                break;

            case MotionEvent.ACTION_MOVE:
                int offx = x - lastX;
                int offy = y - lastY;

//                layout(getLeft() + offx, getTop() + offy
//                        , getRight() + offx, getBottom() + offy);
                // 同時偏移(與layout 方法效果一樣)
                offsetLeftAndRight(offx);
                offsetTopAndBottom(offy);
                /*
                * 注意:一定要重新設置座標,這樣才能準確地獲取偏移量
                */
                lastX = x;
                lastY = y;

                break;
        }
        return true;//記得返回true,說明被我們這裏消化了改事件
    }

}
發佈了101 篇原創文章 · 獲贊 8 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章