kawazaki :
I am inside a fragment and when i click on the enter key(in the keyboard) , I want to hide the keyboard. I have tried this but doesn't work
<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);
}
Jakob :
First create a hideSoftKeyboard()
void.
public void hideSoftKeyboard() {
if(getCurrentFocus()!=null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
Then set OnEditorActionListener
to the edittext
and call hideSoftKeyboard()
.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN ))){
hideSoftKeyboard();
return true;
}
else{
return false;
}
}
});
Finally we add some XML attributes to the 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"/>