Saturday, August 25, 2012

Working with Button and its event...

We looked at Hello World program which describes TextView widget. Let's have a look at Button.

In this program we'll perform Button's click event and we'll display number of clicks in TextView.

1. Design layout

You can see I have taken one Button and a TextView on screen. You can see XML code in below screen.

I have used Linear Layout with vertical orientation to design it.

2. Add or create resources
Here in this program I have created some resources which you can see in below screen.

3. Write Class File
 For this design we have a class file to access and code for controls in layout. Take a look at below screen.

Here I have taken a class named Counter which extends Activity class. int counter = 0; is used to count number of clicks on button.

In the method onCreate objects of Button and TextView is created. findViewById( is a method which fetch control from layout and we cast this to button object. Class R is used to access resources of your project in your Java file. Here Button is a View in layout and we are accessing it with

After creating objects I have written an OnClickListener method for button. After writing this event, each time you press button this event will fire. In this listener method I have incremented counter.

I have written this program to make you understand findViewById and OnClickListener method. 

View findByViewById(int id) is method of Activity class which looks for child view with given ID.  If id found it will return View which ultimately casted to respective object.

setOnClickListener(OnClickListener ocl) is a method of button object which executes every time button pressed.

Thats it. You're done!!!

No comments:

Post a Comment