【问题标题】:i can't closing my app with back button because onKeyDown() method我无法使用后退按钮关闭我的应用程序,因为 onKeyDown() 方法
【发布时间】:2021-08-06 08:55:36
【问题描述】:

我编写了一个代码来运行事件处理程序,但是我遇到了一个问题,我无法使用后退按钮关闭我的应用程序

package bahrudin.bagus.inputevents

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
}

// if i use this method, then i can't close app with back button
// otherwise, if I don't use this method, then I can close the app with back button
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_DOWN -> Toast.makeText(applicationContext, "Volume Down Key Pressed", Toast.LENGTH_SHORT).show()
            KeyEvent.KEYCODE_VOLUME_UP -> Toast.makeText(applicationContext, "Volume Up Key Pressed", Toast.LENGTH_SHORT).show()
            KeyEvent.KEYCODE_BACK -> Toast.makeText(applicationContext, "Back Key Pressed", Toast.LENGTH_SHORT).show()
        }
        return true
    }

如何在仍然使用此方法的同时关闭我的应用程序?

谢谢:)

【问题讨论】:

    标签: android kotlin event-handling event-listener


    【解决方案1】:

    您可以使用将 KEYCODE_BACK 代码更改为此

    KeyEvent.KEYCODE_BACK -> {
        Toast.makeText(applicationContext, "Back Key Pressed", Toast.LENGTH_SHORT).show()
        // finish() //one of these 2, not both, it usually depends on the behavior you need, since you can override back press to a desired behavior as well
        // super.onBackPressed()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2019-12-17
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多