Interactivity

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. 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. At the top of our class, declare a field TextView hoursLeftTextView;.
  4. In onCreate, just below setContentView, do the lookup:
    hoursLeftTextView = findViewById(R.id.hoursLeftTextView);
  5. Next, update the text to “X hours left”:
    hoursLeftTextView.setText("X hours left");

Note: in Kotlin, skip step 3 and 4. See Kotlin version for info.

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:
    public void onChangeDeadlineClicked(View viewThatWasClicked) {
        hoursLeftTextView.setText("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 (int) (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

LF