NAYIR55
NAYIR55

Reputation: 105

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

I'm working on a project to make calculations. So, I have my EditText box working, and I want to hide the softkeyboard 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?

Upvotes: 0

Views: 332

Answers (1)

hakim
hakim

Reputation: 3909

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;
    }
};

Upvotes: 1

Related Questions