按下时按下ACTION_DOWN和UP

时间:2017-10-10 18:26:05

标签: android click

我创建了一个用于检测按钮被释放或单击的类。

现在我需要在ImageButton中更改图像,单击按钮以及何时释放。

问题出在这里,如果我按下按钮,同时激活MotionEvent.ACTION_DOWN和MotionEvent.ACTION_UP,当发布时,我收到ACTION_DOWN事件。

为什么我在点击时收到2个事件,只有在释放时才收到?

button.setOnTouchListener( new View.OnTouchListener() 
{
    public boolean onTouch(View v, MotionEvent event) 
    {
        switch (event.getAction()) 
        {
            case MotionEvent.ACTION_DOWN: 
            {
                Log.d("log", "onTouch: push");
                button.setImageResource(R.drawable.buttonmason);
            }

            case MotionEvent.ACTION_UP: 
            {
                Log.d("log", "onTouch: release");
                button.setImageResource(R.drawable.buttonmas);
            }
        }

        if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoIncrement )
        {
            mAutoIncrement = false;
        }
        else if((event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL)  && mAutoDecrement )
        {
            mAutoDecrement = false;
        }

        return false;
    }
});

1 个答案:

答案 0 :(得分:0)

以下是带有break语句的修订代码

button.setOnTouchListener( new View.OnTouchListener() 
{
    public boolean onTouch(View v, MotionEvent event) 
    {
        switch (event.getAction()) 
        {
            case MotionEvent.ACTION_DOWN: 
            {
                Log.d("log", "onTouch: push");
                button.setImageResource(R.drawable.buttonmason);
            }
            break
            case MotionEvent.ACTION_UP: 
            {
                Log.d("log", "onTouch: release");
                button.setImageResource(R.drawable.buttonmas);
            }
        }

        if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoIncrement )
        {
            mAutoIncrement = false;
        }
        else if((event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL)  && mAutoDecrement )
        {
            mAutoDecrement = false;
        }

        return false;
    }
});