Help us understand the problem. What is going on with this article?

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

More than 3 years have 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

iotlt
IoT縛りの勉強会です。 毎月イベントを実施しているので是非遊びに来てください! 登壇者を中心にQiitaでも情報発信していきます。 https://iotlt.connpass.com
https://iotlt.connpass.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away