Interactivity (Kotlin)

Even though we have a fancy layout now, the button doesn’t do anything. How can we write code that updates the text when the button is clicked? Actually, setContentView(…); in MainActivity returns nothing at all, so how can we even access our views from the code?

The solution is to give every view an ID, and then do a lookup to get hold of them. Kotlin will do the lookup for us. Look in the Java version of this page if you want to do it manually.

Let’s start with the text:

  1. In activity_main.xml, click the text view.
  2. Change the ID at the top of the Attributes panel to something like “hoursLeftTextView” or whatever you like. (If Studio asks to update references in XML code, answer Yes.)
  3. Next, update the text to “X hours left”:
    hoursLeftTextView.text = "X hours left"
    // Studio will import from kotlinx when you write this line.

Run the app again. You should see that the text is now “X hours left”. Now, let’s change the time left every time we click the button!

  1. Write a method to handle button clicks in MainActivity, and move the setText line there:
    fun onChangeDeadlineClicked(viewThatWasClicked: View) {
        hoursLeftTextView.text = "X hours left"
  2. In activity_main.xml, click our button and select onChangeDeadlineClicked for the onClick attribute. Now, Android knows what to do when the button is clicked. Run the app and try it out!
  3. Use Math.round(Math.random() * 100) to get a random number in [0, 100]. Display that number instead of X.

Run our deadline app. It’s cool to have numbers changing all the time, but it’s not very useful. Can we count down toward a real deadline instead?

Next: Setting and showing a deadline