Created
September 30, 2015 11:46
-
-
Save theredfox/c11c200f38b60d00de54 to your computer and use it in GitHub Desktop.
EditText with KeyBoard detector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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