Android execute function after pressing “Enter” fo

2019-02-08 15:49发布

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 EditText.

I understand what I'm supposed to do and seem to have everything setup properly, but Eclipse is complaining with this line:

edittext.setOnKeyListener(new OnKeyListener() {

It underlines setOnKeyListener with the error:

The method setOnKeyListener(View.OnKeyListener) in the type View is not applicable for the arguments (new DialogInterface.OnKeyListener(){})

And also underlines OnKeyListener with the error:

The type new DialogInterface.OnKeyListener(){} must implement the inherited abstract method DialogInterface.OnKeyListener.onKey(DialogInterface, int, KeyEvent)

Perhaps someone can shoot me in the right direction? Before I try other solutions (which I've already found on stackoverflow), I'd really like to figure this out because it has me flustered that something so simple to follow, as an official tutorial, doesn't seem work.

Thanks in advance.

3条回答
神经病院院长
2楼-- · 2019-02-08 16:12

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;
查看更多
够拽才男人
3楼-- · 2019-02-08 16:22

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;
    }
});
查看更多
Lonely孤独者°
4楼-- · 2019-02-08 16:30

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

查看更多
登录 后发表回答