Skip to content

Instantly share code, notes, and snippets.

@pyro2927
Created October 9, 2014 19:58
Show Gist options
  • Save pyro2927/ea21a8f3b575fc180cff to your computer and use it in GitHub Desktop.
Save pyro2927/ea21a8f3b575fc180cff to your computer and use it in GitHub Desktop.
I just want 'enter' to dismiss the keyboard :(
public class DismissiveEditText extends EditText implements View.OnKeyListener, TextView.OnEditorActionListener {
public DismissiveEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public DismissiveEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DismissiveEditText(Context context) {
super(context);
init();
}
private void init(){
this.setOnKeyListener(this);
this.setOnEditorActionListener(this);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new DismissiveInputConnection(super.onCreateInputConnection(outAttrs),
true);
}
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) &&
(i == KeyEvent.KEYCODE_ENTER)) {
clearFocus();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER) {
clearFocus();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (keyEvent != null&& (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
clearFocus();
}
return false;
}
private class DismissiveInputConnection extends InputConnectionWrapper {
public DismissiveInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
clearFocus();
return false;
}
return super.sendKeyEvent(event);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment