在本文中,我们将学习如何以编程方式隐藏软键盘。键盘通常是隐藏的,但在某些情况下不会隐藏。因此,为了获得更好的用户体验,可以通过编程方式隐藏键盘。
在不使用以下方法的情况下,该应用的默认响应如下所示:-
方法:
- 现在,将以下代码添加到activity_main.xml文件中。下面的代码在activity_main中添加了一个textview , edittext和一个按钮。单击该按钮时,将调用MainActivity类中的setText函数。
activity_main.xml
MainActivity.java
package org.geeksforgeeks.gfgHideKey import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.inputmethod .InputMethodManager; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView textViewResult; private EditText editTextInput; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResult = findViewById( R.id.text_view_result); editTextInput = findViewById( R.id.edit_text_input); } public void setText(View v) { String newText = editTextInput .getText() .toString(); textViewResult.setText(newText); closeKeyboard(); editTextInput.setText(""); } private void closeKeyboard() { // this will give us the view // which is currently focus // in this layout View view = this.getCurrentFocus(); // if nothing is currently // focus then this will protect // the app from crash if (view != null) { // now assign the system // service to InputMethodManager InputMethodManager manager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); manager .hideSoftInputFromWindow( view.getWindowToken(), 0); } } }
- 现在,在MainActivity中添加以下代码。 Java文件。在这里,我们定义了setText和closeKeyboard函数。当用户单击按钮时,将调用setText函数。它从edittext获取输入,并将其替换在textview中。然后,它调用closeKeyboard函数并清除edittext的值。 closeKeyboard函数隐藏键盘。
主要活动。Java
package org.geeksforgeeks.gfgHideKey import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.inputmethod .InputMethodManager; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView textViewResult; private EditText editTextInput; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResult = findViewById( R.id.text_view_result); editTextInput = findViewById( R.id.edit_text_input); } public void setText(View v) { String newText = editTextInput .getText() .toString(); textViewResult.setText(newText); closeKeyboard(); editTextInput.setText(""); } private void closeKeyboard() { // this will give us the view // which is currently focus // in this layout View view = this.getCurrentFocus(); // if nothing is currently // focus then this will protect // the app from crash if (view != null) { // now assign the system // service to InputMethodManager InputMethodManager manager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); manager .hideSoftInputFromWindow( view.getWindowToken(), 0); } } }
输出: