Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not allowed to use setOnClickListener in this situation?

This makes no sense, I am given an error saying that setOnClickListener can't be applied to MainActivity. But i've made other projects where I've never encountered this problem. What's going on?

public class MainActivity extends ActionBarActivity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    button = ((Button) findViewById(R.id.button));

    button.setOnClickListener(this);

}
like image 276
That Thatson Avatar asked Mar 27 '15 15:03

That Thatson


2 Answers

You have to declare MainActivity like this:

public class MainActivity extends ActionBarActivity implements View.OnClickListener

and after that you have to override the onClick method in MainActivity

@Override
public void onClick(View v) {
     //do something...
} 
like image 116
Niccolò Passolunghi Avatar answered Sep 22 '22 20:09

Niccolò Passolunghi


As we can see you havn't implemented the View.OnClickListener on Main activity.. this will be used as MainActivity but the parameter that can be passed is OnClickListener

SideNote: Always try to typecast before you use, this greatly reduce the complications and sometimes takes you to mistakes you are doing.

like image 36
Ankit Bansal Avatar answered Sep 22 '22 20:09

Ankit Bansal