Here is a short guide to use buttons and textView in kotlin android. If you're a java dev who is trying to switch to kotlin then this guide is made for you. If you're a new to android development then refer to Google Developers (opens new window).
Start by creating a button in layout like you do usually :
<Button android:id="@+id/toast_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Toast Button" />
I gave it an ID of
toast_buttonso that we can reference it in code. Now navigate to the kotlin file of that activity or fragment.
val toastButton = findViewById<Button>(R.id.toast_button)
This is how we reference a button object in kotlin. Let me compare it to java for you.
Button toastButton = (Button) findViewById(R.id.toast_button);
No much difference right ? remember that
val in kotlin cannot be reassigned. That means it's similar to
final object in java. So bascially the kotlin code above is :
final Button toastButton = (Button) findViewById(R.id.toast_button);
Which cannot be reassigned again. What if you want it to change. In that case use
var instead of
var age = 3 age = 5 age = 7
var can be reassigned but if you try to reassign val you'll get a warning ⚠ saying that val cannot be reassigned.