Skip to content Skip to sidebar Skip to footer

Setonclicklistener Not Working And Throwing Error

Below is my program and I am getting this error: Description Resource Path Location Type The method setOnClickListener(View.OnClickListener) in the type View is not applic

Solution 1:

You are passing your Activity class as the OnClickListener in this line:

exitBtn.setOnClickListener(this);

However, your class needs to explicitly declare that it is implementing the View.OnCLickListener interface. Change your class declaration line to this:

publicclasswelcomeextendsActivityimplementsOnClickListener

A couple of other things to note:

You wrote playBtn.setOnItemClickListener(). Perhaps you meant playBtn.setOnClickListener(this)? Buttons don't have OnItemClickListeners

You can also set an OnClickListener without having the activity class itself implement the interface by declaring an anonymous class. Like this:

playBtn.setOnClickListener(newOnClickListener() {
    publicvoidonClick(View v) {
        // playBtn code
    }
});

exitBtn.setOnClickListener(newOnClickListener() {
    publicvoidonClick(View v) {
        // exitBtn code
    }
});

This way is used more often because it is more readable. By segregating the button onClick code, you can easily tell which button does what, as opposed to putting it all into one method and having the class itself implement OnClickListener.

Solution 2:

Button playBtn = (Button) findViewById(R.id.playBtn);
playBtn.setOnItemClickListener();

It should be setOnClickListener(this), as done for the Exit Button. Does exit button work?

Solution 3:

You are setting common onClick method for both OnClickListener classes that is wrong. Try to have two different onClick methods for both button's OnClickListener class.

Solution 4:

If you want to use this as exitBtn.setOnClickListener(this);, you have to declare that your Activity will implements the interface OnClickListener

publicclasswelcomeextendsActivityimplementsOnClickListener {
...
}

Solution 5:

Try this instead:

publicvoidonCreate(Bundle savedInstanceState)
   {
   super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome1);


    //////// MENU  //////////Button playBtn = (Button) findViewById(R.id.playBtn);
    playBtn.setOnItemClickListener(newView.OnClickListener() {
        publicvoidonClick(View v) {
            i = newIntent(this, testcalculator.class);
            startActivity(i);
        }
    });

    Button exitBtn = (Button) findViewById(R.id.exitBtn);
    exitBtn.setOnClickListener(newView.OnClickListener() {
        publicvoidonClick(View v) {
            finish();
        }
    });
}

Or change your class to implement the OnClickListener like: public class welcome extends Activity implements OnClickListener

Post a Comment for "Setonclicklistener Not Working And Throwing Error"