키보드 작업 처리
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Compose 사용해 보기
Jetpack Compose는 Android에 권장되는 UI 도구 키트입니다. Compose에서 키보드 작업을 처리하는 방법을 알아보세요.
사용자가 EditText
요소와 같은 수정 가능한 텍스트 뷰에 포커스를 맞추는 경우 하드웨어 키보드가 연결되어 있으면 모든 입력이 시스템에서 처리됩니다. 하지만 앱에서 키보드 입력을 가로채거나 직접 처리하게 만들려면 KeyEvent.Callback
인터페이스에서 onKeyDown()
과 onKeyMultiple()
같은 콜백 메서드를 구현하면 됩니다.
Activity
클래스와 View
클래스 모두 KeyEvent.Callback
인터페이스를 구현하므로 일반적으로 이 클래스의 확장에서 적절하게 콜백 메서드를 재정의합니다.
참고: KeyEvent
클래스 및 관련 API를 사용하여 키보드 이벤트를 처리할 때는 키보드 이벤트가 하드웨어 키보드에서만 발생한다고 예상해야 합니다. 소프트 입력 방법 (터치 키보드)에서 발생하는 키 이벤트를 수신한다고 생각해서는 안 됩니다.
단일 키 이벤트 처리
개별 키 누르기를 처리하려면 적절하게 onKeyDown()
또는 onKeyUp()
를 구현합니다. 일반적으로 이벤트를 하나만 수신하려면 onKeyUp()
을 사용합니다. 사용자가 키를 길게 누르면 onKeyDown()
이 여러 번 호출됩니다.
예를 들어 다음 구현은 게임을 제어하는 일부 키보드 키에 응답합니다.
Kotlin
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_D -> {
moveShip(MOVE_LEFT)
true
}
KeyEvent.KEYCODE_F -> {
moveShip(MOVE_RIGHT)
true
}
KeyEvent.KEYCODE_J -> {
fireMachineGun()
true
}
KeyEvent.KEYCODE_K -> {
fireMissile()
true
}
else -> super.onKeyUp(keyCode, event)
}
}
자바
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_D:
moveShip(MOVE_LEFT);
return true;
case KeyEvent.KEYCODE_F:
moveShip(MOVE_RIGHT);
return true;
case KeyEvent.KEYCODE_J:
fireMachineGun();
return true;
case KeyEvent.KEYCODE_K:
fireMissile();
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
특수키 처리
키를 Shift 또는 Control 키와 함께 사용하는 작업처럼 특수키 이벤트에 응답하려면 콜백 메서드에 전달된 KeyEvent
를 쿼리하면 됩니다. getModifiers()
및 getMetaState()
와 같은 몇 가지 메서드를 통해 특수키와 관련된 정보를 얻을 수 있습니다.
하지만 가장 간단한 해결 방법은 isShiftPressed()
와 isCtrlPressed()
와 같은 메서드를 사용하여 중요한 특수키가 정확히 눌렸는지 확인하는 것입니다.
예를 들어 다음 onKeyUp()
구현에서는 Shift 키를 누른 채로 또 다른 키를 사용할 경우 이를 어떻게 추가적으로 처리할 수 있는지를 보여줍니다.
Kotlin
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
...
KeyEvent.KEYCODE_J -> {
if (event.isShiftPressed) {
fireLaser()
} else {
fireMachineGun()
}
true
}
KeyEvent.KEYCODE_K -> {
if (event.isShiftPressed) {
fireSeekingMissle()
} else {
fireMissile()
}
true
}
else -> super.onKeyUp(keyCode, event)
}
}
Java
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
...
case KeyEvent.KEYCODE_J:
if (event.isShiftPressed()) {
fireLaser();
} else {
fireMachineGun();
}
return true;
case KeyEvent.KEYCODE_K:
if (event.isShiftPressed()) {
fireSeekingMissle();
} else {
fireMissile();
}
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
추가 리소스
-
단축키 도우미: 사용자가 앱에서 제공하는 단축키를 검색할 수 있는 시스템 화면입니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-26(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-26(UTC)"],[],[],null,["# Handle keyboard actions\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to handle keyboard actions in Compose. \n[Handle keyboard actions in Compose →](/develop/ui/compose/touch-input/keyboard-input/commands#key_events) \n\nWhen the user gives focus to an editable text view, such as an\n[EditText](/reference/android/widget/EditText)\nelement, and the user has a hardware keyboard attached, all\ninput is handled by the system. However, if you want to intercept\nor directly handle the keyboard input yourself, you can do so by implementing callback methods\nfrom the [KeyEvent.Callback](/reference/android/view/KeyEvent.Callback)\ninterface, such as [onKeyDown()](/reference/android/view/KeyEvent.Callback#onKeyDown(int, android.view.KeyEvent))\nand [onKeyMultiple()](/reference/android/view/KeyEvent.Callback#onKeyMultiple(int, int, android.view.KeyEvent)).\n\nBoth the [Activity](/reference/android/app/Activity)\nand [View](/reference/android/view/View) classes implement the\n`KeyEvent.Callback` interface, so you\ngenerally override the callback methods in your extension of these classes, as\nappropriate.\n\n**Note:** When handling keyboard events with the\n[KeyEvent](/reference/android/view/KeyEvent) class and related APIs,\nexpect that the keyboard events are coming only from a hardware keyboard. Never rely on receiving key\nevents for any key on a soft input method (an on-screen keyboard).\n\nHandle single key events\n------------------------\n\nTo handle an individual key press, implement\n[onKeyDown()](/reference/android/app/Activity#onKeyDown(int, android.view.KeyEvent))\nor [onKeyUp()](/reference/android/app/Activity#onKeyUp(int, android.view.KeyEvent)),\nas appropriate. Usually, you use\n`onKeyUp()`\nif you want to ensure that you receive only one event. If the user presses and holds a key,\nthen `onKeyDown()` is called multiple times.\n\nFor example, this implementation responds to some keyboard keys to control a game: \n\n### Kotlin\n\n```kotlin\noverride fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {\n return when (keyCode) {\n KeyEvent.KEYCODE_D -\u003e {\n moveShip(MOVE_LEFT)\n true\n }\n KeyEvent.KEYCODE_F -\u003e {\n moveShip(MOVE_RIGHT)\n true\n }\n KeyEvent.KEYCODE_J -\u003e {\n fireMachineGun()\n true\n }\n KeyEvent.KEYCODE_K -\u003e {\n fireMissile()\n true\n }\n else -\u003e super.onKeyUp(keyCode, event)\n }\n}\n```\n\n### Java\n\n```java\n@Override\npublic boolean onKeyUp(int keyCode, KeyEvent event) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_D:\n moveShip(MOVE_LEFT);\n return true;\n case KeyEvent.KEYCODE_F:\n moveShip(MOVE_RIGHT);\n return true;\n case KeyEvent.KEYCODE_J:\n fireMachineGun();\n return true;\n case KeyEvent.KEYCODE_K:\n fireMissile();\n return true;\n default:\n return super.onKeyUp(keyCode, event);\n }\n}\n```\n\nHandle modifier keys\n--------------------\n\nTo respond to modifier key events, such as when a key is combined with \u003ckbd\u003eShift\u003c/kbd\u003e\nor \u003ckbd\u003eControl\u003c/kbd\u003e, you can\nquery the `KeyEvent`\nthat is passed to the callback method. Several methods\nprovide information about modifier keys, such as\n[getModifiers()](/reference/android/view/KeyEvent#getModifiers())\nand [getMetaState()](/reference/android/view/KeyEvent#getMetaState()).\nHowever, the simplest solution is to check whether\nthe exact modifier key you care about is being pressed with methods such as\n[isShiftPressed()](/reference/android/view/KeyEvent#isShiftPressed())\nand [isCtrlPressed()](/reference/android/view/KeyEvent#isCtrlPressed()).\n\nFor example, here's the `onKeyUp()` implementation\nagain, with extra handling for when the \u003ckbd\u003eShift\u003c/kbd\u003e key is held down with one of the keys: \n\n### Kotlin\n\n```kotlin\noverride fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {\n return when (keyCode) {\n ...\n KeyEvent.KEYCODE_J -\u003e {\n if (event.isShiftPressed) {\n fireLaser()\n } else {\n fireMachineGun()\n }\n true\n }\n KeyEvent.KEYCODE_K -\u003e {\n if (event.isShiftPressed) {\n fireSeekingMissle()\n } else {\n fireMissile()\n }\n true\n }\n else -\u003e super.onKeyUp(keyCode, event)\n }\n}\n```\n\n### Java\n\n```java\n@Override\npublic boolean onKeyUp(int keyCode, KeyEvent event) {\n switch (keyCode) {\n ...\n case KeyEvent.KEYCODE_J:\n if (event.isShiftPressed()) {\n fireLaser();\n } else {\n fireMachineGun();\n }\n return true;\n case KeyEvent.KEYCODE_K:\n if (event.isShiftPressed()) {\n fireSeekingMissle();\n } else {\n fireMissile();\n }\n return true;\n default:\n return super.onKeyUp(keyCode, event);\n }\n}\n```\n\nAdditional resources\n--------------------\n\n- [Keyboard Shortcuts Helper](/develop/ui/compose/touch-input/keyboard-input/keyboard-shortcuts-helper): System screen that enables users to search the keyboard shortcuts your app offers."]]