Android Using Buttons and Ways to Handling Event

In android development life-cycle, Button view is most common view used on activity. This article shows you basic types of Button view and how we can implement event handlers in different ways.

Lets create layout xml first with some Buttons.

main.xml

Implementing onClick handlers in various ways.

Handling Event Way 1

Notice the first button (Button 1) has the android:id attribute. To handle the click event programmatically, refer the button and call its setOnClickListener method, then set to it an instace of the OnClickListener class. Under the class implement onClick() method;

Handling Event Way 2

The next button is same like Button 2. Only the the difference is, instead of creating inner class of event handler, an anonymous class is created here.

And then set it to click event handler to this class.

Handling Event Way 3

The third Button has android:onClick.

And set to onBtnClick() method which is declared in activity.

Handling Event for Toggle Button

The ToggleButton is same like Basic Button, Only the difference is it shows it’s state toggled (true/false) indicating by blue/green line depends on theme you selected.

Android Using Buttons and Ways to Handling Event

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *