Android View拖拽跟随手指移动
2020-05-08 本文已影响0人
Android刘东
package test.view;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.zhisheng.test.R;
/**
* 实现功能根据手指滑动
*/
public class MyView extends View {
int x1=0, x2=0, y1=0, y2=0;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public MyView(Context context) {
super(context);
init(context);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
void init(Context context) {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
onMyTouch(event);
return true;
}
void onMyTouch(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
y1 = (int)event.getY();
x1 = (int)event.getX();
break;
case MotionEvent.ACTION_MOVE:
x2 = (int)event.getX();
y2 = (int)event.getY();
layout(x2-x1+getLeft(), y2-y1+getTop(), x2-x1+getRight(), y2-y1+getBottom());
break;
}
}
}