Coding Time

So I’ve started with the attribute parameters I knew the view would need to initiate itself. I wanted to decide how many stars I want for my view, what colors the stars would be. What would be the minimum and maximum star sizes, and what is the size above which a star will be considered a big star.

class AnimatedStarsView

@kotlin.jvm.JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {



private var starCount: Int

private var starColors: IntArray

private var bigStarThreshold: Int

private var minStarSize: Int

private var maxStarSize: Int }

We will initiate the actual stars, only after we know the view’s size, and every time the view’s size changes.

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {

super.onSizeChanged(w, h, oldw, oldh)

viewWidth = w

viewHeight = h



if (viewWidth > 0 && viewHeight > 0) {

// init stars every time the size of the view has changed

initStars()

}

} /**

* create x stars with a random point location and opacity

*/

private fun initStars() { stars = List(starCount) { // star constructor

Star(

starConstraints,

Math.round(Math.random() * viewWidth).toInt(), // x

Math.round(Math.random() * viewHeight).toInt(), // y

Math.random(), // opacity

starColors[it % starColors.size], // color

viewWidth,

viewHeight,

// random color function

{ starColors[random.nextInt(starColors.size)] }

) // so we know lateinit var was initiated

initiated = true } }

Notice how we initialize the list with the List constructor — courtesy of Dominik Mičuta & Arek Olek, who pointed this out in the comments below.

It takes a function, that will iterate over the starCount , and will init a new Star object for every iteration. This is instead of initiating the list, then running a for loop to add each star “manually”.

We will also do something similar for generating a random color, for each new Star when passing the last Star parameter. Instead of implementing an interface , we will just pass a fun to be invoked.