在 EditText 外单击时隐藏键盘,可以通过设置 android:windowSoftInputMode
为 stateHidden
或者 stateAlwaysHidden
的方式来实现。另外,还可以使用一些额外的布局技巧和事件监听器来实现这个功能。
具体实现方式如下:
AndroidManifest.xml
文件中设置 android:windowSoftInputMode
属性:
<activity android:windowSoftInputMode="stateHidden" ... />
LinearLayout
或者 RelativeLayout
中,并设置 android:layout_alignParentEnd
属性,同时将 Button 或者其他的视图放置在 EditText 的右边,并设置 android:layout_alignParentStart
属性,来让它们在键盘弹出时能够收起。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true">
<EditText android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:hint="Input text" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
EditText editText = findViewById(R.id.edit_text);
Button button = findViewById(R.id.button);
// 注册点击事件监听器
editText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 隐藏键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 隐藏键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
这样一来,当你在 EditText 中输入文本时,单击其他区域就可以隐藏键盘了。
领取专属 10元无门槛券
手把手带您无忧上云