I have an Activity, where I want the software keyboard to be alaways opened. How to close the Activity after BACK press, when keyboard is opened? Now I have to click BACK twice, first to close the keyboard and then to finish the Activity.
As mentioned, onKeyPreIme can be used to catch the back button, but this needs to be overridden on the text view, not in the activity.
Here's a complete solution:
First a new class that derived from EditText, overrides onKeyPreIme and calls a callback interface:
// EditTextWithBackButton class
public class EditTextWithBackButton extends EditText
{
public interface IOnBackButtonListener
{
boolean OnEditTextBackButton();
}
public EditTextWithBackButton(Context context)
{
super(context);
}
public EditTextWithBackButton(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setOnBackButtonListener(IOnBackButtonListener l)
{
_listener = l;
}
IOnBackButtonListener _listener;
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event)
{
if (event.getAction()==KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_BACK)
{
if (_listener!=null && _listener.OnEditTextBackButton())
return false;
}
return super.onKeyPreIme(keyCode, event); //To change body of overridden methods use File | Settings | File Templates.
}
}
Next, update your layout:
<com.yournamespace.whatever.EditTextWithBackButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textField"
/>
Next, update your activity, inside OnCreate, after setContentView:
((EditTextWithBackButton) findViewById(R.id.textField)).setOnBackButtonListener(new EditTextWithBackButton.IOnBackButtonListener()
{
@Override
public boolean OnEditTextBackButton()
{
finish();
return true;
}
});
Use onKeyPreIme(int keyCode, KeyEvent event) method and check for KeyEvent.KEYCODE_BACK event. It's very simple without doing any fancy coding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With