how to add button click event in android studio
package com.mani.smsdetect;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
//Declaration Button
Button btnClickMe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Intialization Button
btnClickMe = (Button) findViewById(R.id.btnClickMe);
btnClickMe.setOnClickListener(MainActivity.this);
//Here MainActivity.this is a Current Class Reference (context)
}
@Override
public void onClick(View v) {
//Your Logic
}
}
Button button= (Button)findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
// click handling code
}
});
SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:
public class Main extends ActionBarActivity implements View.OnClickListener {
// do your stuff
}
This:
buttonname.setOnClickListener(this);
means that you want to assign listener for your Button "on this instance" ->
this instance represents OnClickListener and for this reason your class have to implement that interface.
It's similar with anonymous listener class (that you can also use):
buttonname.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});