Notes: 06. Handle Click Events
Try adding two buttons that increment and decrement the glass count by 0.5 respectively. These buttons can be smaller in size and located below the existing buttons. You can improve the UI by making the “-1” button visible only if the glass count is greater than zero.
On Wear OS, a click listener to also a modifier. To add click listeners on the buttons, first open the WaterService and add the following modifier in the imageButton method:
.setClickable(
ModifiersBuilders.Clickable.builder()
.setId(id)
.setOnClick(ActionBuilders.LoadAction.builder())
)
Here, you use the setClickable method to set a click listener on the Layout Element. ModifiersBuilders.Clickable.builder() is similar to the builders used for other modifiers. A Clickable modifier has two main properties:
First is id: The id is used to identify the element that was clicked. In this case, you are reusing the element id. You can set the id to any other string as well.
And second, OnClick Action: The Actions specifies the result of clicking the element. LoadAction reloads the tile which is exactly what we need to show the updated glass count.
The setModifiers method should now be as follows:
.setModifiers(
ModifiersBuilders.Modifiers.builder()
.setBackground(
ModifiersBuilders.Background.builder()
.setColor(
ColorBuilders.argb(ContextCompat.getColor(this, R.color.colorPrimary))
)
.setCorner(ModifiersBuilders.Corner.builder().setRadius(BUTTON_RADIUS).build())
.build()
)
.setPadding(
ModifiersBuilders.Padding.builder()
.setAll(dp(4f))
.build()
)
.setClickable(
ModifiersBuilders.Clickable.builder()
.setId(id)
.setOnClick(ActionBuilders.LoadAction.builder())
)
)
Whenever the tile is reloaded, the onTileRequest method is invoked. Inside onTileRequest, you can perform the operations corresponding to the clicks.
Add the following code inside onTileRequest, right before invoking waterRepository.getGlassCount():
when(requestParams.state.lastClickableId) {
ID_IMAGE_PLUS_ONE -> waterRepository.incrementFullGlass()
ID_IMAGE_MINUS_ONE -> waterRepository.decrementFullGlass()
}
In this code, you are fetching the id of the last clicked element using requestParams.state.lastClickableId. You are then comparing the id with those of the buttons and invoking the corresponding methods.
If the Tile was not loaded due to a click event, requestParams.state.lastClickableId will return an empty string. Build and run the app. Click on the plus or minus button. You can see that the glass count is updated when you click the buttons.
Congratulations, you have successfully created a functional tile for Wear OS.