NAYIR55 NAYIR55 - 1 month ago 18
Android Question

Android - How to hide softkeyboard if EditText is empty on key press?

I'm working on a proyect to make calculations. So, I have my EditText box working, and I want to hide the softkwyboard if the user clicks the DONE (or any other kind of button, GO, NEXT, etc.) and the EditText box is empty

Like so:

EditText is empty -> user clicks button -> softkeyboard hides

I have this piece of code that I manage to write using tutorials and guides over the internet

I do know it is to manage the listener of the button in the softkeyboard

TextView.OnEditorActionListener mEditor = new TextView.OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if (actionId == EditorInfo.IME_ACTION_DONE)
{
//Calculations method
}

return false;
}
};


So, my question is: How can I manage the listener when the EditText is empty and not get errors?

Answer

you can use, for example:

TextView.OnEditorActionListener mEditor = new TextView.OnEditorActionListener()
{
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
    {
        if (actionId == EditorInfo.IME_ACTION_DONE)
        {
            if (!TextUtils.isEmpty(v.getText().toString())){
                // you calculations method
            } else {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }

        return false;
    }
};