2
0

More than 1 year has passed since last update.

【Android】キーボード関連の処理

Last updated at Posted at 2022-03-03

はじめに

キーボード関連の処理をメソッド形式でメモ。

コード

キーボード表示状態の確認

fun keyboardVisibility(view: View) =
	view.height > Rect().apply { view.getWindowVisibleDisplayFrame(this) }.height()

キーボードの表示

fun showKeyboard(editText: EditText) {
	editText.requestFocus()
	val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
	imm.showSoftInput(editText, 0)
}

キーボードの非表示

fun hideKeyboard() {
	val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
	imm.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
	currentFocus?.clearFocus()
}

キーボード表示状態変更リスナー

fun View.setKeyboardListener() {
	this.viewTreeObserver.addOnGlobalLayoutListener {
		val keyboardVisibility = keyboardVisibility(this)
		if (keyboardVisibility) {
			Toast.makeText(applicationContext, "open", Toast.LENGTH_SHORT).show()
		} else {
			Toast.makeText(applicationContext, "close", Toast.LENGTH_SHORT).show()
		}
	}
}

キーボード表示状態変更リスナー
※リスナー実行後、リスナーを削除する場合

fun View.setKeyboardListener() {
	this.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
		override fun onGlobalLayout() {
			val keyboardVisibility = keyboardVisibility(this@setKeyboardListener)
			if (keyboardVisibility) {
				Toast.makeText(applicationContext, "open", Toast.LENGTH_SHORT).show()
			} else {
				Toast.makeText(applicationContext, "close", Toast.LENGTH_SHORT).show()
			}
			//処理実行後、リスナーを無効にする
			this@setKeyboardListener.viewTreeObserver.removeOnGlobalLayoutListener(this)
		}
	})
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0