Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 가상 키보드(소프트 키보드)를 닫거나 숨기는 방법

Android에서 가상 키보드(소프트 키보드)를 닫거나 숨기는 방법

Android 앱을 개발하다 보면 EditText에 포커스가 있는 상태에서도 기본 키보드를 강제로 닫아야 하는 경우가 종종 발생합니다. 이번 글에서는 InputMethodManager를 활용해 가상 키보드를 프로그래밍 방식으로 숨기는 방법을 단계별 예제와 함께 살펴보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계: 레이아웃 작성 (res/layout/activity_main.xml)

다음 코드를 res/layout/activity_main.xml 파일에 추가합니다. 화면 상단에는 텍스트를 입력받을 EditText를, 중앙에는 키보드를 숨기는 버튼을 배치했습니다.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android ="https://schemas.android.com/apk/res/android"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">
    <EditText
        android:id = "@+id/editext"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content">
    </EditText>
    <Button
        android:id = "@+id/button"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Click here to hide"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

3단계: MainActivity.java 구현

src/MainActivity.java 파일에 아래 코드를 추가합니다. 앱이 시작되면 EditText에 포커스를 요청해 키보드를 띄우고, 버튼 클릭 시 hideKeyboard() 메서드를 통해 키보드를 닫습니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        EditText editext = findViewById(R.id.editext);
        editext.requestFocus();
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                hideKeyboard(v);
                break;
        }
    }

    private void hideKeyboard(View v) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
    }
}

핵심 로직은 바로 위의 hideKeyboard() 메서드 두 줄입니다.

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

InputMethodManager의 hideSoftInputFromWindow() 메서드에 현재 뷰의 윈도우 토큰(getApplicationWindowToken())을 전달하면, 화면에 떠 있는 소프트 키보드가 즉시 닫힙니다. 이것이 Android에서 키보드를 강제로 숨기는 가장 일반적인 방식입니다.

4단계: 매니페스트 설정 (AndroidManifest.xml)

매니페스트 파일의 액티비티 태그에 windowSoftInputMode 속성을 아래와 같이 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication">
    <application
        android:allowBackup = "true"
        android:icon = "@mipmap/ic_launcher"
        android:label = "@string/app_name"
        android:roundIcon = "@mipmap/ic_launcher_round"
        android:supportsRtl = "true"
        android:theme = "@style/AppTheme">
        <activity android:name = ".MainActivity" android:windowSoftInputMode = "stateAlwaysVisible">
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />
                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

windowSoftInputMode를 "stateAlwaysVisible"로 지정하면 EditText가 포커스를 받을 때마다 키보드가 자동으로 나타납니다. 덕분에 버튼을 눌렀을 때 키보드가 실제로 숨겨지는지 명확하게 확인할 수 있습니다.

앱 실행 및 결과 확인

실제 Android 기기를 컴퓨터에 연결한 뒤, Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭합니다. 실행 대상으로 연결된 모바일 기기를 선택하면 앱이 설치되고, 아래와 같이 키보드가 표시된 기본 화면을 볼 수 있습니다.

Android에서 가상 키보드(소프트 키보드)를 닫거나 숨기는 방법

이제 버튼을 클릭해 보세요. 아래 그림과 같이 키보드가 즉시 사라지는 것을 확인할 수 있습니다.

Android에서 가상 키보드(소프트 키보드)를 닫거나 숨기는 방법

추가 팁

반대로 앱 시작 시 키보드를 처음부터 표시하지 않으려면 windowSoftInputMode 값을 "stateHidden" 또는 "stateAlwaysHidden"으로 변경하면 됩니다. 또한 최신 Android(API 30 이상)에서는 WindowInsetsCompat API를 활용하면 키보드의 표시 여부와 높이를 더욱 유연하게 제어할 수 있으니 참고하시기 바랍니다.