Android/Java
[Java] InputMethodManager
혀가 길지 않은 개발자
2020. 8. 25. 16:48
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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.java
package com.jwsoft.javaproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private Button btnShowKeyboard;
private Button btnCloseKeyboard;
private EditText etContents;
private InputMethodManager inputMethodManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowKeyboard = findViewById(R.id.btnShowKeyboard);
btnCloseKeyboard = findViewById(R.id.btnCloseKeyboard);
etContents = findViewById(R.id.etContents);
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
btnShowKeyboard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etContents.requestFocus(); // 포커스가 있어야 키보드가 노출됨.
inputMethodManager.showSoftInput(etContents, InputMethodManager.SHOW_IMPLICIT);
}
});
btnCloseKeyboard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
inputMethodManager.hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS
);
}
});
}
}