Reputation: 4714
I want to achieve a simple task of unfocusing EditText
(not hide cursor) when keyboard is dismissed, either by hitting the done or the return button. All I can find so far is
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
But it is only good when the activity is first opened up. After keyboard is dismissed, text field is left in an awkward focused state.
Upvotes: 5
Views: 2392
Reputation: 4660
Kotlin version:
class CustomEditText: AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
if(keyCode == KeyEvent.KEYCODE_BACK) {
clearFocus()
}
return super.onKeyPreIme(keyCode, event)
}
}
Usage:
<com.youappdomain.view.CustomEditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Upvotes: 0
Reputation: 36373
I can't believe this is the easiest solution I could find to this problem (really, Android?):
public class CustomEditText extends EditText {
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == KeyEvent.KEYCODE_ENDCALL) {
InputMethodManager imm = (InputMethodManager)v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(CustomEditText.this.getWindowToken(), 0);
CustomEditText.this.clearFocus();
return true;
}
return false;
}
});
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
this.clearFocus();
}
return super.onKeyPreIme(keyCode, event);
}
}
Upvotes: 3
Reputation: 357
You can clear the focus from edit text and also manage the enable/disable edit text.
Upvotes: 0
Reputation: 4386
You could listen for an event when keyboard is dismissed and then use editText.clearFocus();
when that event happens.
Refer to this answer for listening to keyboard dismiss events
Upvotes: 4