DC5Gator DC5Gator - 2 months ago 11
Android Question

Cannot Resolve (or Import Andriod Widget) OnEditorActionListener

I am new to coding and keep getting errors when trying to use OnEditorActionListener to help perform an action once the user inputs data into EditText and presses "Go" on the softkeyboard. I have searched and most solutions offered assume that OnEditorActionListener is already imported.

Articles used as a guide to generate my own code:



My XML Code:

<requestFocus />

My Java Code (snippet):

import android.widget.TextView.OnEditorActionListener;

EditText editTextListener = (EditText) findViewById(R.id.editTextCurrentBalance);
editTextListener.setOnEditorActionListener(new OnEditorActionListener(){...});

First Error: " import android.widget.TextView.OnEditorActionListener; " gives me an error that says "Unused Import Statement" and the whole line of code is grey'd out.

Second Error: " Cannot Resolve Symbol 'setOnEditorActionListener' "

Fix Attempt: When I press CTRL + I, I get a message "No methods to implement have been found".

Appreciate any help!

UPDATE: My Java Code for the OnEditorActionListener was outside of the OnCreate method brackets. Once put inside, the errors cleared up.


Hello and welcome to SO

1st error: well this is actually not an error, it's just a warning your IDE is giving you meaning you have imported a class you are not using. It's a good practice to remove any unused imports (Ctrl + Alt + O in Android Studio)

2nd error: I believe this one is popping up because you haven't imported EditText class, but I'm not sure

Anyway, take a loot at this

//We are import the classes you need here
import android.widget.EditText;
import android.widget.TextView;

//here is just the onCreate method from an Activity, 
//I have left out most of the boilerplate code

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        //grabing the EditText object by it's ID you defined in the layout file
        //I have renamed the object to "editText" because "listener" 
        //suffix made no sense here, it's an EditText class you are 
        //crating, which is not a listener 
        EditText editText = (EditText) findViewById(R.id.editTextCurrentBalance);

        //here we are creating a new anonymous class and setting to
        //trigger when an "Editor Action" happens on editTextListener
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                //do something here
                return false;

Anonymous classes are just a simpler way of creating a new class if we don't intent to reuse that class somewhere else ie. it's specific to your current need

Hope this helps :) and good luck learning Android and Java