:
, , ,
I tested my code, it works fine.
Step 1: Create CustomEditTextas shown below.
<com.yourpackage.yourappname.CustomEditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Step 2: Create a Class CustomEditText.java.
public class CustomEditText extends EditText {
Context context;
private static Activity mSearchActivity;;
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if(mSearchActivity != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK){
KeyEvent.DispatcherState state = getKeyDispatcherState();
if(state != null){
if(event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0){
InputMethodManager mgr = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
else if(event.getAction() == KeyEvent.ACTION_UP && !event.isCanceled() && state.isTracking(event)){
mSearchActivity.onBackPressed();
return true;
}
}
}
return super.dispatchKeyEventPreIme(event);
}
}
Step 3: In your activity, configure CustomEditText and hide the KeyBoard, as shown below.
CustomEditText editText = (CustomEditText) findViewById(R.id.edittext);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Step 4: In your activity, just a Overridemethod onBackPressed().
@Override
public void onBackPressed() {
super.onBackPressed();
}
user5248371
source
share