Capture button release in Android

后端 未结 5 1809
我寻月下人不归
我寻月下人不归 2020-12-01 17:55

Is it possible to capture release of a button just as we capture click using onClickListener() and OnClick() ?

I want to increase size of a

相关标签:
5条回答
  • 2020-12-01 18:18

    You have to handle MotionEvent.ACTION_CANCEL as well. So the code will be:

    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP || 
                event.getAction() == MotionEvent.ACTION_CANCEL) {
                increaseSize();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                resetSize();
            }
        }
    };
    
    0 讨论(0)
  • 2020-12-01 18:19

    Eric Nordvik has the right answer except that

    event.getAction() == MotionEvent.ACTION_UP
    

    never got executed for me. Instead I did implement

        button.setOnClickListener(new OnClickListener() {
            @Override
            public boolean onClick(View v) {
                resetSize();      
        }
    };
    

    for the touch ACTION_UP.

    0 讨论(0)
  • 2020-12-01 18:33

    use an OnTouchListener or OnKeyListener instead.

    0 讨论(0)
  • 2020-12-01 18:33

    You might be able to do this by overriding the onKeyDown and onKeyUp. These are both inherited from android.widget.TextView. Please see the android.widget.Button doc for (a bit) more info.

    0 讨论(0)
  • 2020-12-01 18:41

    You should set an OnTouchListener on your button.

    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
                increaseSize();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                resetSize();
            }
        }
    };
    
    0 讨论(0)
提交回复
热议问题