简体   繁体   English

按Enter时清除EditText

[英]clear EditText when Enter is pressed

I want to clear an EditText when i click a button or press Enter. 我想在单击按钮或按Enter时清除EditText。 It works fine with the button, but when pressing Enter, it clears both the EditText and TextView. 它可以很好地与按钮配合使用,但是当按下Enter键时,它将同时清除EditText和TextView。

I appreciate any help. 感谢您的帮助。 Thank you. 谢谢。

public void onClick(View v) {
        textViewEcho.setText(editTextInput.getText().toString());
        editTextInput.setText("");
    }

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode == 66) {
        textViewEcho.setText(editTextInput.getText().toString());
        editTextInput.setText("");
    }
    return false;
}

Update: i found out that onKey is called twice, that's why the TextView's content is cleared, but can't figure out why onKey is called twice, is this a bug in Android?!!!!! 更新:我发现onKey被调用两次,这就是为什么TextView的内容被清除的原因,但无法弄清楚为什么onKey被调用两次,这是Android中的错误吗?

i tried onKeyUp instead, it does work. 我尝试了onKeyUp,它确实可以工作。

edittext.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_ENTER) 
//write the code what ever u want when u press enter                {
edittext.setText("");

                }

                return false;
            }
        });

try this, need to return true. 试试这个,需要返回true。

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode == 66) {
        String txt = editTextInput.getText().toString();
        textViewEcho.setText(txt);
        editTextInput.setText("");
        return true; // return the true from here
    }
    return false;
}

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

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