The keyboard is one of the basic components of any Android application. Typically, we use the keyboard to take input from the user. Soft keyboards are used in Android applications, and the Android system gives you with a keyboard to receive user input in any EditText or anything similar. Also, the keyboard will be invisible from the screen if the user has given input. So, in this blog, we will learn how to check if keyboard appears in Android app. How can I make this keyboard invisible or turn it off if it is visible?. So, let’s get started.
Step 1 − Create a new project in Android Studio, Add the following code to activity_main.xml.
Step 2 − Add the following code to MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ConstraintLayout constraintLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
EditText editText=findViewById(R.id.editext);
editText.requestFocus();
constraintLayout=findViewById(R.id.main_layout);
constraintLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
constraintLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = constraintLayout.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.15) {
Toast.makeText(MainActivity.this,"Keyboard is showing",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"keyboard closed",Toast.LENGTH_LONG).show();
}
}
});
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
hideSoftkeybard(v);
break;
}
}
private void hideSoftkeybard(View v) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
Here, we are using hideSoftKeyboard to hide the keyboard if the keyboard is visible on clicking the button.
So, finally, run the application and see the output on your mobile device.
In this blog, we learned how to check if the keyboard is visible or not on the screen. Also, we have if the keyboard is visible then how to close it. That’s it for this blog.