Android Android Code Snippets Blog Button Code Snippets onClickListener setOnClickListener ToggleButton

Android Using Buttons and Ways to Handling Event

In android improvement life-cycle, Button view is commonest view used on exercise. This text exhibits you primary forms of Button view and how we will implement event handlers in several ways.

Lets create format xml first with some Buttons.

principal.xml

Implementing onClick handlers in numerous ways.

Handling Event Method 1

Discover the first button (Button 1) has the android:id attribute. To handle the press occasion programmatically, refer the button and call its setOnClickListener technique, then set to it an instace of the OnClickListener class. Underneath the class implement onClick() technique;

Handling Event Means 2

The subsequent button is similar like Button 2. Solely the the distinction is, as an alternative of making internal class of occasion handler, an anonymous class is created here.

After which set it to click event handler to this class.

Handling Event Means three

The third Button has android:onClick.

And set to onBtnClick() technique which is said in exercise.

Handling Event for Toggle Button

The ToggleButton is similar like Primary Button, Only the difference is it exhibits it’s state toggled (true/false) indicating by blue/inexperienced line will depend on theme you selected.