我无法使用后退按钮关闭我的应用程序,因为 onKeyDown() 方法
i can't closing my app with back button because onKeyDown() method
我为 运行 事件处理程序编写了一个代码,但是我遇到了一个问题,我无法使用后退按钮关闭我的应用程序
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
}
如何在仍然使用此方法的同时关闭我的应用程序?
谢谢:)
您可以将 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()
}
我为 运行 事件处理程序编写了一个代码,但是我遇到了一个问题,我无法使用后退按钮关闭我的应用程序
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
}
如何在仍然使用此方法的同时关闭我的应用程序?
谢谢:)
您可以将 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()
}