Android execute function after pressing “Enter” for EditText

前端 未结 3 928
鱼传尺愫
鱼传尺愫 2021-01-02 02:24

I have been following the official Android tutorials and somehow am having a problem with this very simple example to execute a function after pressing \"Enter\" for an Edit

相关标签:
3条回答
  • 2021-01-02 02:50

    From what I can see, It looks like you have the wrong import.

    Try

    edittext.setOnKeyListener(new View.OnKeyListener() {
    

    OR add this import

    import android.view.View.OnKeyListener;
    

    and Remove this one

    import android.content.DialogInterface.OnKeyListener;
    
    0 讨论(0)
  • 2021-01-02 03:04

    Delete the import statement that has DialogInterface, then import the View.OnKeyListener.

    0 讨论(0)
  • 2021-01-02 03:15

    To receive a keyboard event, a View must have focus. To force this use:

    edittext.setFocusableInTouchMode(true);
    edittext.requestFocus();
    

    After that continue with the same code in the example:

    edittext.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                (keyCode == KeyEvent.KEYCODE_ENTER)) {
              // Perform action on key press
              Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
              return true;
            }
            return false;
        }
    });
    
    0 讨论(0)
提交回复
热议问题