Android EditText键盘收起

在Android应用开发中,EditText是常用的用户输入组件之一。用户在EditText中输入文本时,通常会弹出软键盘,以便用户输入文字。但有时候我们希望在用户输入完成后,手动隐藏软键盘。本文将介绍如何通过代码实现EditText键盘的收起。

使用InputMethodManager类

在Android中,可以通过InputMethodManager类来控制软键盘的显示和隐藏。下面是一个简单的示例代码,演示了如何在用户点击按钮时隐藏软键盘:

// 获取InputMethodManager实例
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// 隐藏软键盘
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

在上面的代码中,我们首先获取了InputMethodManager实例,并调用hideSoftInputFromWindow()方法来隐藏软键盘。其中editText是需要隐藏软键盘的EditText组件。

示例应用

接下来我们将通过一个简单的示例应用来演示如何实现EditText键盘的收起。首先,在activity_main.xml中添加一个EditText和一个Button组件:

<EditText
    android:id="@+id/edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<Button
    android:id="@+id/hide_keyboard_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hide Keyboard"/>

然后在MainActivity.java中,我们通过点击按钮来隐藏软键盘:

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private Button hideKeyboardButton;

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

        editText = findViewById(R.id.edit_text);
        hideKeyboardButton = findViewById(R.id.hide_keyboard_button);

        hideKeyboardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
            }
        });
    }
}

结语

通过以上示例代码,我们实现了在用户点击按钮时隐藏软键盘的功能。在实际应用中,可以根据具体的需求来触发软键盘的显示和隐藏操作。希望本文对您理解Android EditText键盘的收起有所帮助。