Wednesday, June 13, 2012

Event Handling

What are events? Why do we need to handle them? Events occur when an user interact with the UI components of our app like buttons. When these events occurs, a function/method is called. As a programmer, it is our responsibility to dump a block of code inside that method/function and make the UI respond to the user, like closing the application when the user presses the "quit" button. Seems like a good idea. Lets do just that.


Create a project. First, we need to include a button in our layout and id it. I do the same in the following code:




In our source code ( java file ), we need to add a variable for this button and add a listener to it, which is done in the following code:



This can also be done another way. Instead of adding OnClickListener on the java file, we can handle events by addding the tag android:onClick="myOnClickMethod". "myOnClickMethod" is a method defined inside our activity class(java file). Any name can be given to the method but it must have an argument of type "View". Take a look at my button in layout and the method myOnClickMethod() in my activity class:

A code snippet for button:







The Activity:


These methods are enough to implement event listeners for 2 or 3 buttons. But what if we need to handle the events of 10 buttons. For this situation, there is a special way of implementing listeners. Lets say we have 4 buttons and a text view as in the layout below. We need to print the event occurred like printing "Button 1 is pressed" when button1 is pressed. What we do is that, we make our activity to implement a class "View.OnClickListener" and then, we implement the common method onClick(), in which we differentiate events occurred by using id of the buttons. This is done in the code given below.


main.xml




BaseActivity.java

Some snaps:


1. The quit button:






2. Button2 event:






3. Button4 event:








OK... thats it for now guys!!! See ya later with more.....

No comments:

Post a Comment