Search code examples
androidandroid-edittext

How to remove focus from EditText when user is done editing?


I have a single EditText on my layout. After the user inputs some text and hits the "done" key, I would like to remove the blinking cursor from it. I have scoured StackOverflow and found 3 answers that didn't work for me. The blinking cursor still remains.

private class MyOnKeyListener implements OnKeyListener {
  public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN
    && keyCode == KeyEvent.KEYCODE_ENTER) {
      // FAIL 0
      MyActivity.this.findViewById(R.id.someOtherView).requestFocus();

      // FAIL 1
      InputMethodManager imm = (InputMethodManager)getSystemService(
        Context.INPUT_METHOD_SERVICE
      );
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

      // FAIL 2
      MyActivity.this.getWindow().setSoftInputMode(
        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
      );

      return true;
    } else {
      return false;
    }
  }
}

Solution

  • You could use a xml attribute,

    android:cursorVisible 
    

    or you can do it in code with this method.

     setCursorVisible(boolean).