개발새발 - IT 기술블로그
article thumbnail

안녕하세요. 이번 포스팅에서는 EditText를 클릭 하였을 때 자동으로 보여지는 입력 키패드를  수동으로 컨트롤하는 예제를 진행해보겠습니다.

 

 


1. 결과 GIF

먼저, 결과 화면을 보시겠습니다. 아래 GIF 처럼 특정 이벤트가 발생하였을 때 EditText에 포커스를 주고 키보드를 올리고 내리는 방식으로 구현 할 수 있습니다.

 

 

 

 

2. 전체코드

레이아웃 파일엔 EditText와 키패드를 올리는 버튼, 내리는 버튼을 각각 1개씩 생성하였습니다.

 

 

KeyboardController.kt

<kotlin />
object KeyboardController { // 키보드 올리기 fun upKeyboard(context: Context, et: EditText) { val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager et.requestFocus() inputMethodManager.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT) } // 키보드 내리기 fun downKeyboard(context: Context, et: EditText) { val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager et.clearFocus() inputMethodManager.hideSoftInputFromWindow(et.windowToken, InputMethodManager.HIDE_IMPLICIT_ONLY) } }

 

 

MainActivity.kt

<kotlin />
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val et: EditText = findViewById(R.id.editText) val up: Button = findViewById(R.id.upBtn) val down: Button = findViewById(R.id.downBtn) up.setOnClickListener { upKeyboard(this, et) } down.setOnClickListener { downKeyboard(this, et) } } }

 

 

3. 코드설명

 

EditText의 포커스를 주입시킵니다. EditText가 입력 가능한 상태로 전환됩니다.

<kotlin />
requestFocus()

 

EditText의 포커스를 해제시킵니다. 입력 불가상태로 전환됩니다.

<kotlin />
clearFocus()

 

InputMethodManager 객체의 매서드입니다. SHOW_IMPLICIT으로 Show를 강제하였습니다.

<kotlin />
inputMethodManager.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT)

 

마찬가지로 InputMethodManager 객체의 매서드입니다. HIDE_IMPLICIT_ONLYHide를 강제하였습니다.

<kotlin />
inputMethodManager.hideSoftInputFromWindow(et.windowToken, InputMethodManager.HIDE_IMPLICIT_ONLY)

 

 

이렇게 키보드의 컨트롤을 수동으로 동작시키는 방법에 대해 알아보았습니다. 

 

감사합니다.

 

 

 

4. 예제 소스

 

https://github.com/tekken5953/KeyBoardControllExam

 

GitHub - tekken5953/KeyBoardControllExam

Contribute to tekken5953/KeyBoardControllExam development by creating an account on GitHub.

github.com