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 varieties of Button view and how we will implement event handlers in several ways.

Lets create format xml first with some Buttons.

most important.xml

Implementing onClick handlers in numerous methods.

Handling Event Approach 1

Notice 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. Beneath the class implement onClick() technique;

Handling Event Approach 2

The subsequent button is similar like Button 2. Only the the difference is, as an alternative of making internal class of occasion handler, an nameless class is created here.

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

Handling Event Method 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 distinction is it exhibits it’s state toggled (true/false) indicating by blue/green line will depend on theme you selected.