Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Activity with software keyboard after BACK press?

Tags:

android

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.

like image 823
fhucho Avatar asked Feb 07 '11 12:02

fhucho


2 Answers

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;
    }
});
like image 154
Brad Robinson Avatar answered Oct 26 '22 12:10

Brad Robinson


Use onKeyPreIme(int keyCode, KeyEvent event) method and check for KeyEvent.KEYCODE_BACK event. It's very simple without doing any fancy coding.

like image 41
Umair Avatar answered Oct 26 '22 11:10

Umair