当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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?

网友答案:

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;
    }
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: