Create Once. Use Everywhere, with Custom Views: Part 3.

Create Once. Use Everywhere, with Custom Views: Part 3.

In the previous articles, we've done a bit of setting up and having our custom view interface come to life.

To have a recap check out these articles Part 1 Part 2

From here we will be adding responsiveness to our layout and let's begin by adding click listeners to our increment and decrement button to trigger events for updating the edit text value.

You can then try it out and at this point, it should work basically incrementing and decrementing values and the default value is set at 0 on decrementing the value won't go below that as we are only interested in positive values.

Listen to events

For the view to communicate with other app components and remain decoupled it needs a way of listening and responding to events such as when the value decreases and increases, an interface would have come in handy, but this being Kotlin we will take the high road with high order functions😜.

So what this does is provides a high order function named valueListner that takes in a value that will be acted upon on events.

Next, there's a new variable introduced called currentValue this follows kotlins property accessor syntax while setting the value and once the value is set it updates the edit text value with the current value.

We then have a high order function called setListener() that takes in a function to initialise our defined listener and retrieveValue() is where the current value is passed to the listener.

With that, we are all set to start using our listener to react to increment and decrement events.

counter.gif

Next up we will look at how to publish all this functionality as a library and use it across your projects

See you then...🤓

Part 4

Project on Github