Kotlin series has been developed keeping in mind, you are already familiar at least at beginner’s level.
This is the Fourth milestone towards our Kotlin series. Go to the third if you haven’t done so.
In this milestone˜, we will simply follow the coding challenges developed for the Android Developer Fundamentals Course, Unit 1 — Lesson2.
How to create and start activities?
- Basically, starting other activities are same as in Java.
val intent = Intent(this, SecondActivity::class.java)
val message = editText_main!!.text.toString()
intent.putExtra(EXTRA_MESSAGE, message)
startActivityForResult(intent, TEXT_REQUEST)
- However, the way we declare final static variables in Kotlin is by using val rather than var.
private val LOG_TAG = MainActivity::class.java.simpleName
- Creating Singleton object in kotlin by using companion object
companion object {
// Class name for Log tag
private val LOG_TAG = FirstActivity::class.java.simpleName
// Unique tag required for the intent extra
val EXTRA_MESSAGE = "EXTRA_MESSAGE"
// Unique tag for the intent reply
val TEXT_REQUEST = 1
}
- Accessor in Kotlin: We don’t have getters and setters so we get a direct access to the field variables. For eg; to getText from the editTextView.
val reply = editText_second.text.toString()
- Setting text in EditText should be done with setText(). Looks like when Kotlin tries to generate synthetic property for a Java getter/setter pair Kotlin first looks for a getter. Since, getter has Editable, we cannot directly use field access.
editText_second.setText(reply)
- The source code: Starting Activity
- The source code: LifeCycle Activity
How to handle implicit intent?
- Resolving the activity for implict intent. We can directly access the packageManager property without getter.
// Find an activity to hand the intent and start that activity.
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
Log.d("ImplicitIntents", "Can't handle this intent!")
}
- The source code: Implicit Intents
- The source code: Implicit Intents Receiver
The fifth milestone in this series.
5. Testing your app in Kotlin (Coming soon)
References:
- Using Kotlin for Android development ~ Kotlin.org
- Resources to Learn Kotlin ~ developer.android
- Why switch to Kotlin? ~ Medium blog
- Kotlin libraries list~ Kotlin.org
- Video of Lectures ~ youtube.com
- How does Kotlin property access syntax work? stackoverflow.com