Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EditText with KeyBoard detector
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by mirkopinna on 26/09/15.
*/
public class EditTextKBDetector extends EditText {
public static final String KEYBOARD_HIDE_EVENT = "keyboard.hidden.event";
public static final String KEYBOARD_SHOW_EVENT = "keyboard.showing.event";
public EditTextKBDetector(Context context) {
super(context);
init();
}
public EditTextKBDetector(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EditTextKBDetector(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
//Has focus keyboard is showing
fireKBShownEvent();
} else {
//Doesn't have focus, keyboard is not showing
fireKBHiddenEvent();
}
}
});
setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
//Keyboard closed with done button
clearFocus();
//fireKBHiddenEvent();
}
return false;
}
});
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
//Keyboard closed with back button
clearFocus();
//fireKBHiddenEvent();
}
return super.dispatchKeyEvent(event);
}
private void fireKBShownEvent() {
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(KEYBOARD_SHOW_EVENT));
}
private void fireKBHiddenEvent() {
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(KEYBOARD_HIDE_EVENT));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment