如何在多个CustomView中处理MotionEvent.ACTION_MOVE?

时间:2018-12-17 15:36:55

标签: java android

我是Java和android开发的新手,我想创建一个包含多个CustomViews的基本应用程序,在这里我可以移动在画布上绘制的不同形状。
我的想法是拥有一个处理MotionEvents并将其传递给各个CustomViews的类。

我的CustomView类:

public class CustomView extends View implements MoveDetector.OnMoveListener {
private MoveDetector mMoveDetector;

public CustomView(Context context) {
    super(context);

}

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

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs);
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init(attrs);
}
private void init(@Nullable AttributeSet set){
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.parseColor("#626696"));
}
@Override
public boolean onTouchEvent(MotionEvent event){
    switch (event.getAction()){
        case MotionEvent.ACTION_MOVE:
            mMoveDetector = new MoveDetector(this);
            mMoveDetector.onTouchEvent(event);
            float cx = mMoveDetector.getCx();
            float cy = mMoveDetector.getCy();
            Toast.makeText(getContext(),"why u packin heat bro?"+Float.toString(cx)+"    "+Float.toString(cy),Toast.LENGTH_SHORT).show();
            Log.d("Moveee", "Move: " + Float.toString(cx)+"    " + Float.toString(cy));
    }
    return super.onTouchEvent(event);
}

@Override
public void OnMove(MoveDetector moveDetector) {
}
}

我的MoveDetector类:

public class MoveDetector {
private float cx,cy, mCislo1,mCislo2;

public float getCx() {
    return mCislo1;
}

public float getCy() {
    return mCislo2;
}

private OnMoveListener mListener;

public MoveDetector(OnMoveListener listener){
    mListener = listener;
}

public boolean onTouchEvent(MotionEvent event) {
    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_MOVE:
            float x = event.getX();
            float y = event.getY();
            mCislo1 = cXX(x);
            mCislo2 = cYY(y);

            if (mListener != null) {
                mListener.OnMove(this);
            }

            break;
    }
return true;}
public static interface OnMoveListener {
    public void OnMove(MoveDetector moveDetector);
}
public float cXX(float x){
    cx = x;
    return cx;
}
public float cYY(float y){
    cy = y;
    return cy;
}
}

它似乎不起作用,我也无法指出原因。 我搜索了很长一段时间的解决方案,但找不到。
所以,如果有人能帮助我,我将非常感激。
P.S .:对不起,如果我的代码很乱:我还在学习。

0 个答案:

没有答案