简体   繁体   English

Android-如果按键时EditText为空,如何隐藏软键盘?

[英]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 因此,我有EditText框,并且如果用户单击DONE(或任何其他类型的按钮,GO,NEXT等)并且EditText框为空,则我想隐藏softkeyboard

Like so: 像这样:

EditText is empty -> user clicks button -> softkeyboard hides EditText为空->用户单击按钮->软键盘隐藏

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 我知道这是在softkeyboard上管理按钮的侦听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? 因此,我的问题是:当EditText为空并且没有收到错误时,如何管理侦听器?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM