在onClick事件之后启动onTouchEvent

时间:2012-05-18 03:09:31

标签: java android imagebutton ontouchevent

我正在尝试在我的Activity中设置图像按钮(pushClick)以启用用于旋转针图形的onTouchEvents。不幸的是,无论是否单击图像按钮,onTouchEvent都处于活动状态。如何在单击图像按钮之前阻止onTouchEvent触发?

public void pushClick(View pushClick) {
    switch (pushClick.getId()) {
    case R.id.btn_push:

        make(degrees);

    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        startRotating();
        break;
    case MotionEvent.ACTION_UP:
        stopRotating();
        break;
    }

    return super.onTouchEvent(event);
}

private void startRotating() {
    returnRotating = false;

    if (!keepRotating) {
        keepRotating = true;

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (keepRotating) {
                    degrees = (degrees + 1) % 360;
                    make(degrees);

                    handler.postDelayed(this, INTERVAL);
                }
            }
        }, INTERVAL);
    }
}

private void stopRotating() {
    keepRotating = false;

    if (!returnRotating) {
        returnRotating = true;

        final Handler handler = new Handler();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (returnRotating) {
                    degrees = (degrees - 1) % 360;
                    make(degrees);

                    handler.postDelayed(this, INTERVAL);
                }
            }
        }, INTERVAL);
    }
}

2 个答案:

答案 0 :(得分:1)

我敢打赌,有更好的方法可以做到这一点,但这是我的头脑:

private boolean buttonClicked = false;

public void pushClick(View pushClick) {
    switch (pushClick.getId()) {
    case R.id.btn_push:
        buttonClicked = true;
        make(degrees);

    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if(buttonClicked)
    {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            startRotating();
            break;
        case MotionEvent.ACTION_UP:
            stopRotating();
            break;
        }
    } 

    return super.onTouchEvent(event);
}

答案 1 :(得分:0)

您还可以在按下图像按钮时添加OnTouchListener(从您想要附加到的任何视图),并在再次单击时将其删除(如果这是您想要的)。