Zafer Celaloglu Zafer Celaloglu - 1 month ago 9
Android Question

How to solve "setOnKeyListener(View.OnKeyListener) in the type View is not applicable for the arguments (new OnKeyListener(){})" error on android?

I'm getting an error with this message "The method setOnKeyListener(View.OnKeyListener) in the type View is not applicable for the arguments (new OnKeyListener(){})"

How can I overcome this problem?

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_first_app);

ListView myListView =(ListView)findViewById(R.id.myListView);

final EditText myEditText =(EditText)findViewById(R.id.myEditText);

final ArrayList<String> toDolist =new ArrayList<String>();

final ArrayAdapter<String> aa;

aa=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,toDolist);

myListView.setAdapter(aa);

myEditText.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {

if(event.getAction()==KeyEvent.ACTION_DOWN)

if(keyCode==KeyEvent.KEYCODE_DPAD_CENTER){
toDolist.add(0,myEditText.getText().toString());

aa.notifyDataSetChanged();

myEditText.setText("");

return true;
}
return false;
}
});

Answer

Change setOnKeyListener as :

myEditText.setOnKeyListener(new EditText.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {

              // your code here 
        }
    });

or import android.view.View.OnKeyListener package to set OnKeyListener for EditText