How to close or hide Soft Keyboard in Android

If you have a case where a user needs to close android soft keyboard when a button is clicked, you can use the code snippet below.

To understand how to hide android soft keyboard in android, we will make use of Android InputMethodManagerwhich offers hideSoftInputFromWindow()method used to close android soft keyboard.

On the other hand, if you want to create a custom soft keyboard in android, you can read our tutorial on how to create custom soft keyboard in android.

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:padding="24dp"
    tools:context=".Button.MainActivity">

    <EditText
        android:id="@+id/fullname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/edit_text"
        android:hint="Full name"
        android:inputType="textNoSuggestions"
        android:padding="12dp"
        android:textColor="#000000"
        android:textColorHint="#848484"
        android:textSize="16sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@color/colorAccent"
        android:onClick="closeKeyboard"
        android:text="Close Soft Keyboard"
        android:textColor="#ffffff"
        android:textSize="15sp"
        android:textStyle="bold" />

</LinearLayout>

MainActivity.java

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.bluapp.androidview.R;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void closeKeyboard(View v){
        try {
            InputMethodManager editTextInput = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            editTextInput.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }catch (Exception e){
            Log.e("AndroidView", "closeKeyboard: "+e);
        }
    }
}

android soft keyboard

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment