티스토리 뷰

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>

activity_main.xml

 

 

 

 

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
            )
        }
    }

}

실행 결과

 

 

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함