非常新手在入门,做的是安卓TV,想判断按了遥控器的确认键。但是发现,其他键都能进入onKeyDown事件,唯独是确认键不会进入onKeyDown事件,如果确实没办法,只能在dispatchKeyEvent拦截了。

override fun dispatchKeyEvent(event: KeyEvent): Boolean {

Log.d("dispatchKeyEvent", "dispatchKeyEvent(), action=" + event.action + " keycode=" + event.keyCode)

return super.dispatchKeyEvent(event)

}

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

when (keyCode) {

KeyEvent.KEYCODE_DPAD_CENTER ->

Toast.makeText(this, "你按下中间键", Toast.LENGTH_SHORT).show()

KeyEvent.KEYCODE_DPAD_DOWN ->

Toast.makeText(this, "你按下下间键", Toast.LENGTH_SHORT).show()

KeyEvent.KEYCODE_DPAD_LEFT ->

Toast.makeText(this, "你按下左方向键", Toast.LENGTH_SHORT).show()

KeyEvent.KEYCODE_DPAD_RIGHT ->

Toast.makeText(this, "你按下右方向键", Toast.LENGTH_SHORT).show()

KeyEvent.KEYCODE_DPAD_UP ->

Toast.makeText(this, "你按下上方向键", Toast.LENGTH_SHORT).show()

KeyEvent.KEYCODE_BACK ->

Toast.makeText(this, "你按下后退键", Toast.LENGTH_SHORT).show()

}

return super.onKeyDown(keyCode, event)

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐