views:

105

answers:

2

I am having a problem right now with setOnClickListener.

When i put this following line:

button.setOnClickListener(this);

And run the application then it does not run and show a message that "Application closed forcefully".

Could you please help me how I can set button onclick event in Android 2.2

Thanks Chandu

A: 

Hi

You can try the below code

button.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) 
  {
      Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
  }    

}

krunal shah
thank you very much for the answers. I got the solution. Actually i was putting the code of the button onclicklistener in Splash screen coding page.Thanks
chandu
A: 

For defining button click event in android, You can try the below code:

public class Main_Activity extends Activity {

private Button myButton;

 @Override
public void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myButton = (Button) findViewById(R.id.Button01);
    myButton.setOnClickListener(new Button_Clicker());
}

class Button_Clicker implements Button.OnClickListener
{
@Override
    public void onClick(View v) {

           if(v==myButton)
       {
                Toast.makeText(v.getContext(), "Hello!! button Clicked", Toast.LENGTH_SHORT).show();

       }    
}
}

}

PM - Paresh Mayani