如何在应用上禁用音量

时间:2015-11-30 16:45:55

标签: android volume updown

我用"上/下"进行测试音量事件,它工作正常,但我有一个问题。

当我点击"转身"音量按钮我的代码工作正常,但是当我按下调低音量按钮时,这就是我在屏幕上看到的内容:

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

如何禁用此功能?

我的代码:

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);
    }
}

1 个答案:

答案 0 :(得分:1)

你必须替换"返回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);
}
}