I have the following code where I want to listen to Volume down key press and do something in the same as in the constraintLayout onClickListener:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide();
textureView = findViewById(R.id.view_finder);
constraintLayout = findViewById<ConstraintLayout>(R.id.screen)
imgCap = findViewById<ImageView>(R.id.imgCapture)
if (allPermissionsGranted()) {
Log.i("PermissionsGranted", "Starting Camera...")
startCamera()
} else {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
private fun startCamera() {
constraintLayout.setOnClickListener { _: View? ->
// do something
}
// do the same thing as ClickListener above if volume down key is pressed
}
I have tried to hack this by overriding onKeyDown but haven't figured out a solution.
CodePudding user response:
Try this:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
//Volume up
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
//Volume down
return true;
default:
return super.dispatchKeyEvent(event);
}
}
And if you want to do the same what on click you can do:
constraintLayout.performClick();