Edited at

Kotlinでbackキー(戻るボタン)のイベントを取る

More than 1 year has passed since last update.

備忘メモ📝


Use setOnKeyListener

view.setOnKeyListener { v, keyCode, event ->

if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
// as you like :)
dismiss()
true
} else {
false
}
}
view.isFocusableInTouchMode = true
view.requestFocus()

途中までview.requestFocus()を書き忘れていて動かなかったので、お忘れなく。👾


Use apply

Kotlinのスコープ関数applyを使うと、よりスッキリ書くことができます。(red_fat_daruma 氏、アドバイスありがとうございます🙇)

view.setOnKeyListener { v, keyCode, event ->

(keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN).apply {
// as you like :)
dismiss()
}
}
view.isFocusableInTouchMode = true
view.requestFocus()


Reference