Today we are going to learn how to use events on androidStudio .
With events like OnClick, OnTouch, or OnKey we can add alot of funcionalities to our app.
We make an easy application, a calculator. But our calculator will not perform calculations yet. It will only show the information of each button in an EditText field while assigning a different sound to each button.
— Click on the different buttons: the button pressed in the field will be displayed.
—Touch each of the different buttons: it will call the OnClick event and show the contents of each button. At the same time, it will show the coordinates of these buttons when you touch them, either touch and hold or touch and scroll (The coordinates will be updated in each displacement).
— Insert by keyboard the button you want to show. In turn, pressing the button assigned to each button will play a sound of its own.
This is how looks the app :
First of all we need to declare the elements we will use (TextView and EditText buttons):
The next step will be to identify each button declared by its ID and assign the listeners of events to each:
Now take a look our events .
To create this event, we will assign a new Button element to identify the id of each button pressed using a switch block.
EditText “result” field will be cleaned.
-In case of clicking on any of the other buttons, its value will be displayed in the result field.
IMPORTANT: I have defined that the maximum field of the EditText is 1 so only 1 value of each button will be shown replacing in case of clicking another one.
As for the previous event, we will need a “btPulsed” button element to call the OnClick method.
It is a switch block through which the coordinates will be displayed:
-When you click on each of the buttons but a different message is sent in each case (Click, keep clicking, and click and drag).
Through an OnKey type event, we will use a switch block to assign a key to each of the buttons. Pressing (we will make sure that the pulsation is of type ACTION_DOWN) will show the content of each button assigned to said key in the EditText “result” and will play a sound of its own. (Own recording of each number and saved in the raw folder.