简体   繁体   中英

How to know if a button is being pressed or released?

I have a little problem when I try to run my Android application. The problem occurs when I push & release a button on my main View. The application is to behave like a portophone (push the button to talk, release to stop).

To notify that the button is pressed or released, I've tried 2 options: - Adding an onClickListener, - Adding an onTouchListener.

The first only looks for the button being pressed, so it's not a viable solution. The second solution is able to differentiate between pushed & released, so it's the one I'm using now. The code looks like this:

// Initialise handler for Push To Talk button
    Button button = (Button) findViewById(R.id.buttonPTT);
    button.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent me){
            switch(me.getAction()){
            case MotionEvent.ACTION_DOWN:
                Toast.makeText(getApplicationContext(), "PTT pressed", Toast.LENGTH_LONG).show();
                // TODO: Activate Push To Talk
                break;
            case MotionEvent.ACTION_UP:
                Toast.makeText(getApplicationContext(), "PTT released", Toast.LENGTH_LONG).show();
                // TODO: End Push To Talk
                break;
            }
            return false;
        }
    });

The problem lies in the ACTION_UP case of the switch. While running, it will only work when you press the button, move the cursor/finger/etc, and then release the button. What I want it to do is press it, and being able to release it without having to move my cursor/finger/etc.

Anybody have any ideas?

Nevermind, I already seem to have found the error. It seemed I still had an onClick handler set in my XML layout file, which I forgot to remove.

Thanks anyway for your time if you read this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM