EditText上完成button的监听器?
如果我有一个EditText,我想听用户是否按下键盘上的“完成”button,我该怎么做?
代码是
final EditText edittext = (EditText) findViewById(R.id.edittext); edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show(); return true; } return false; } });
在那个'edittext'是textfield的id
查看此链接只需将setOnKeyListener设置为您的editText即可
Dinash的答案很好,但它不适用于所有设备。 下面的代码适用于所有设备
edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show(); return true; } return false; } });
同样的琼斯答案,但用replacelambda:
etPointCombatFirst.setOnEditorActionListener((v, actionId, event) -> { if (actionId == EditorInfo.IME_ACTION_DONE) { Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show(); return true; } return false; });