2

I'm testing with "turn up/down" volume events, and it works fine, but I have a question.

When I hit the "turn up" volume button my code works correctly, but when I press the turn down volume button this is what I see on my screen:

http://i.imgur.com/oThipej.jpg

How do I disable this?

My code:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button pregunta;
    private TextView respuesta;

int sino = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pregunta = (Button)findViewById(R.id.pregunta);
    respuesta = (TextView)findViewById(R.id.respuesta);
}

public void responde(View v){

    if(sino == 1){
        respuesta.setText("La respuesta es sí.");
    }else if (sino == 2){
        respuesta.setText("La respuesta es no");
    }else{
        respuesta.setText("Ummmm, no lo veo claro...");
    }

    sino = 0;
}


@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_DOWN) {
                sino = 1;
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                sino = 2;
            }
            return false;
        default:
            return super.dispatchKeyEvent(event);
    }
}
Mike Bonnell
  • 16,181
  • 3
  • 61
  • 77
Aris Guimerá
  • 1,095
  • 1
  • 12
  • 27

1 Answers1

3

you must replace "return false;" to "return true;"

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (action == KeyEvent.ACTION_DOWN) {
            sino = 1;
        }
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_DOWN) {
            sino = 2;
        }
        return true;
    default:
        return super.dispatchKeyEvent(event);
}
}
Luca Ziegler
  • 3,236
  • 1
  • 22
  • 39
  • 1
    To expand on this: Returning `true` signals the program that the event was consumed, meaning that the event fired in your override should run without default subsequent actions being called. – Rein S Nov 30 '15 at 16:58