Android/Kotlin
[Kotlin] InputMethodManager
혀가 길지 않은 개발자
2020. 8. 25. 16:39
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/etContents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="James Kim"
android:textSize="26dp"
android:textStyle="bold" />
<Button
android:id="@+id/btnShowKeyboard"
android:layout_width="220dp"
android:layout_height="65dp"
android:textAllCaps="false"
android:text="Show Keyboard"
android:textSize="20dp"
android:textStyle="italic"
android:layout_marginTop="30dp" />
<Button
android:id="@+id/btnCloseKeyboard"
android:layout_width="220dp"
android:layout_height="65dp"
android:textAllCaps="false"
android:text="Close Keyboard"
android:textSize="20dp"
android:textStyle="italic"
android:layout_marginBottom="300dp"/>
</LinearLayout>
MainActivity.kt
package com.jwsoft.kotlinproject
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var inputMethodManager: InputMethodManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
btnShowKeyboard.setOnClickListener {
etContents.requestFocus() // 포커스가 있어야 키보드가 노출됨.
inputMethodManager.showSoftInput(etContents, InputMethodManager.SHOW_IMPLICIT)
}
btnCloseKeyboard.setOnClickListener {
inputMethodManager.hideSoftInputFromWindow(
currentFocus?.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
}
}
}