Android Architecture Components for Dummies in Kotlin (50 lines of code)

Once upon a time, building Android App is as simple as writing all your code in an Activity, and you are done.

class MainActivity : AppCompatActivity() {
private var count = 0

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
my_container.setOnClickListener { incrementCount() }
}

override fun onResume() {
super.onResume()
incrementCount()
}

private fun incrementCount() {
my_text.text = (++count).toString()
}
}

It’s just a little < 20 lines of code, and you could have an App the display the count increment, as you click, and as you foreground your app.

But like a house drawing above, it is not extensible to a real big project. It has some problems.

  1. If you rotate your device, the count value will be reset.
  2. It is hard to test. We can’t unit test Activity class easily.
  3. Putting everything in a class, will make me a dumb coder. I am a dummy, but I don’t want my code to look like…

--

--