Java 按enter键时将键盘隐藏在片段内
我在一个片段中,当我点击键盘上的回车键时,我想隐藏键盘。我已经试过了,但不起作用Java 按enter键时将键盘隐藏在片段内,java,android,Java,Android,我在一个片段中,当我点击键盘上的回车键时,我想隐藏键盘。我已经试过了,但不起作用 <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:cursorVisible="false" /> edittext.setOnKeyListener(new View.OnKeyListener() { public
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
/>
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
edittext.setOnKeyListener(新视图.OnKeyListener(){
公共布尔onKey(视图v、int keyCode、KeyEvent事件){
//如果事件是“回车”按钮上的按键按下事件
if((event.getAction()==KeyEvent.ACTION\u向下)&&
(keyCode==KeyEvent.keyCode\u ENTER)){
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT\u输入\u状态\u始终\u隐藏);
}
首先创建一个hideSoftKeyboard()
void
public void hideSoftKeyboard() {
if(getCurrentFocus()!=null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
然后将OnEditorActionListener
设置为edittext
并调用hideSoftKeyboard()
最后,我们将一些XML属性添加到edittext
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edittext"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:imeOptions="actionDone"
android:singleLine="true"
android:lines="1"
android:inputType="text"/>
由于软键盘通常不发送按键事件,OnKeyListener通常不起作用。对于操作按钮,请使用onEditorActionListener
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edittext"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:imeOptions="actionDone"
android:singleLine="true"
android:lines="1"
android:inputType="text"/>