SWDesk/App
[Kotlin] Treat Key Event
bizmaker
2024. 6. 14. 15:43
키 이벤트를 처리하기 위한 함수 예시 코드
- override fun dispatchKeyEvent(event: KeyEvent): Boolean
- override fun dispatchGenericMotionEvent(ev: MotionEvent?): Boolean
- override fun onGenericMotionEvent(event: MotionEvent?): Boolean
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
// Check if the event is a key down event
val keyName = KeyEvent.keyCodeToString(event.keyCode)
Log.d("[dispatchKeyEvent()] ", "$keyName @ ${event?.source}")
if (event?.action == KeyEvent.ACTION_DOWN) {
when (event.keyCode) {
KeyEvent.KEYCODE_BACK -> {
// Finish the activity, which will effectively close the app
finish()
return true
}
KeyEvent.KEYCODE_ENTER -> {
if (isWarmingupFinished) {
val intent = Intent(this, GameSelection::class.java)
startActivity(intent)
return true
}
if (isPartImageUpdatable) updatePartImage(false)
if (!isWarmingupStarted) {
isWarmingupStarted = true
ivCountdown.visibility = View.VISIBLE
}
return true
}
KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_UP -> {
// Handle volume keys if needed
return true
}
else -> {
// Handle other keys
val keyName = KeyEvent.keyCodeToString(event.keyCode)
val currentTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
displayText = "Key: $keyName\nTime: $currentTime"
Toast.makeText(applicationContext, displayText, Toast.LENGTH_LONG).show()
Log.d("[Key]", keyName)
// Convert the text to a bitmap and set it to the ImageView
return true
}
}
}
// If the event is not handled, let the system handle it
return super.dispatchKeyEvent(event)
}
override fun dispatchGenericMotionEvent(ev: MotionEvent?): Boolean {
Log.d("[Source]", ev?.source.toString())
if (ev?.source == 8194) {
Log.d("8194", "pushed")
return true
}
return super.dispatchGenericMotionEvent(ev)
}
override fun onGenericMotionEvent(event: MotionEvent?): Boolean {
Log.d("[Source - onGenericMotionEvent]", event?.source.toString())
if (event?.source == 8194) {
Log.d("8194 - onGenericMotionEvent", "pushed")
return false // 이벤트가 처리되었음을 알리기 위해 true를 반환
}
return super.onGenericMotionEvent(event) // 나머지 이벤트는 기본 처리 방식으로 처리
}
반응형