Question

When I press 'Return' key in EditText, it is making new line by making it bigger. How to make EditText lose focus when 'Return' key is pressed? In other words, how to make keyboard disappear when 'Return' is pressed?

Was it helpful?

Solution

Use following short of code to get event of Return and disappear keyboard.

(EditText) findViewById(R.id.editText1)).setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == 66) {
            hideKeyboard(v);
            return true; //this is required to stop sending key event to parent
        }
        return false;
    }
});

In above code 66 is code for Return You can also use KeyEvent.KEYCODE_ENTER as preferred by @JJPA.

Following is code to hide keyboard explicitly.

private void hideKeyboard(View view) {
    InputMethodManager manager = (InputMethodManager) view.getContext()
            .getSystemService(INPUT_METHOD_SERVICE);
    if (manager != null)
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

OTHER TIPS

Avoid displaying the return key if you don't want user to press it.

What you can do is, make the EditText singleLine and play around a little with android:nextFocus* to implement a more user friendly IME navigation. For your problem, you can simply modify your EditText from xml like

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit"
        android:singleLine="true"
/>

You need to use TextWatcher so you can catch the \n character and modify text so there is no new lines, heres the magic:

mFirstEditText.addTextChangedListener( new TextWatcher() {

    private boolean mEnterOccurred;

    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        String textStr = text.toString();
        if(textStr.contains("\n")) {
            // Wipe off the \n
            textStr = textStr.replace("\n", "");
            mEnterOccurred = true;
            mFirstEditText.setText(textStr);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence text, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        if(mEnterOccurred) {
            // Change focus to another EditText
            mSecondEditText.requestFocus();
            // Change flag to default
            mEnterOccurred = false;
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top