Saturday, October 29, 2011

Setting up a button click on Android

In this example, I have a button in my layout XML file that I called bulb1_button.  I want to set up a click event for it.  Below is my code to do this inside the OnCreate method.

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
      // Button 1 clicked event. 
      final Button button1 = (Button)findViewById(R.id.bulb1_button);
      button1.setOnClickListener(new View.OnClickListener()
      {
       
        @Override
        public void onClick(View v)
        {
            // TODO: Actions to take when the button is clicked.           
        }
      });
      // End of Button 1 clicked event.

 

We first define a variable the will hold the button.  I call this one button1 which is of type Button.  Next I set up an event listener to handle the click.  Inside the listener, I create the code to handle the click and place inside of it what happens when the button is clicked.

No comments:

Post a Comment