Are you an Android Developer, and tired of having to explicitly redraw your views every time you change a property? Are you looking for a more "Kotlin" approach to managing your views? Make use of the InvalidatesView delegate to automatically redraw your views when you set a property!
Without InvalidatesView | With InvalidatesView |
---|---|
5 easy steps to get you started.
- Copy
InvalidatesView.kt
into your project. - Update the package name at the top of
InvalidatesView.kt
. - Identify the properties that should trigger an invalidation of the view when changed.
- Use
InvalidatesView
to initialize the value of those View properties. - Make sure to pass in an intial value to
InvalidatesView
(Note thatInvalidatesView
cannot, and should not be used outside of a view!
(some View class)
var arcStyle: Int = 1
--->
var arcStyle: Int by InvalidatesView(1)
As per this discussion thread there are some costs to using this approach. Each field/property with a delegated property will create a new object. Evaluate whether InvalidatesView
is the right option for you, based on how many instances of your view will exist, and how many delegated properties it has.
That's all folks! 🎉
Please leave comments with any feedback and "star" if this was helpful to you!
InvalidatesView.kt
is a Kotlin delegate. If you apply a delegate to a property, it will handle any gets or sets of the property's value. We are extending ReadWriteProperty
to create our delegate for convenience. Delegates can also hold a reference to the object they are used in (that is the thisRef
that you see in InvalidatesView
. In the case of InvalidatesView
we are using this to intercept the set'ing of the property's value and call thisRef.invalidate() to redreaw the view.
Hungry for more Kotlin? Take a bite into this free and interactive course on kotlin.
Distributed under the Apache 2.0 license.
🎈 float free