キーボードがいい感じに引っ込んでくれない
これだとログインボタンを押すことができません...
他の領域にクリックイベントをつけることで解決する
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/upper_space"
android:layout_width="match_parent"
android:layout_height="200dp" />
<EditText
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="ID"/>
<View
android:id="@+id/top_space"
android:layout_width="match_parent"
android:layout_height="30dp" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="パスワード"/>
<View
android:id="@+id/middle_space"
android:layout_width="match_parent"
android:layout_height="30dp" />
<!-- 本当はこの部分にもEditTextがひとつあったのですが今は表示していません -->
<View
android:id="@+id/bottom_space"
android:layout_width="match_parent"
android:layout_height="130dp" />
<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ログイン" />
</LinearLayout>
では,プログラムを書いていきます。
プログラム
他のEditText
がクリックされたときはキーボードを引っ込める必要はないと思ったので,そのときはキーボードを引っ込める処理は行いません。
import android.content.Context
import android.content.Intent
import android.hardware.input.InputManager
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.getSystemService
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
upper_space.setOnClickListener {
this.hideKeyboard()
}
top_space.setOnClickListener {
this.hideKeyboard()
}
middle_space.setOnClickListener {
this.hideKeyboard()
}
bottom_space.setOnClickListener {
this.hideKeyboard()
}
}
private fun hideKeyboard() {
val view = this@LoginActivity.currentFocus
if (view != null) {
val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
スペース部分のView
にクリックイベントをつけて,キーボードを引っ込める関数のhideKeyboard()
を呼び出しています!
これでキーボードが引っ込むようになりました。