Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Adding the OnClick Method2:36 with Ben Deitch
The OnClick method is called when the button is actually clicked (or tapped). Any code in the OnClick method will run each time we tap the button!
We just left off with a lot of code that was generated by auto complete. 0:00 We use on click listeners like this a lot in Android. 0:05 So it'll make more and more sense the more you use it. 0:08 This on click method, 0:11 will run when ever this listener detects a click on our button. 0:14 Just like opening our app triggers the onCreate method, 0:18 typing on our button will trigger this onClick method. 0:21 So anytime we click on our button, 0:24 the code that we write inside these curly brackets will run. 0:26 Let's add a comment in the onClick method to describe what we'd like to do. 0:31 The button was clicked, 0:34 so update the fact TextView with a new fact. 0:38 All right, now we need a new fact. 0:44 On the line below our comment, let's create a new string variable named fact. 0:47 And let's set it equal to in quotation marks Ostriches 0:52 can run faster than horses. 0:57 And don't forget the semicolon. 1:01 Now we need to update our text view to show this new fact. 1:03 Remember when we were editing the layout? 1:07 We can change the text of a text view by editing it's text property or 1:09 by changing it directly in the layout's XML file. 1:13 Android also allows us to make these kinds of changes in code. 1:17 On a new line type factTextView.setText and then hit Enter to autocomplete. 1:21 Notice that there's a list of different parameters down here. 1:30 This is because there are different versions of this set text method. 1:33 Each taken different parameters. 1:38 We want this first one because it only has one parameter for the text. 1:40 Now the data type here, CharSequence, 1:44 might be a little confusing since we're using a String. 1:47 But a String is just a sequence of characters, so 1:51 it shouldn't be too surprising that all Strings are also CharSequences. 1:54 Kind of like how text views are also views or how dogs are also animals. 2:00 In Android, 2:06 whenever you see a Charsequence, you can just pass in a string. 2:07 All right, let's type fact in between the parenthesis to pass in our fact variable 2:11 and now we are ready for the moment of truth. 2:16 Let's click on the Run button, or hit Ctrl + Alt on Mac, 2:18 or Shift + F10 on Windows to run our app. 2:22 Looks good. 2:27 Let's click on the button to test it. 2:29 Did you know that ostriches can run faster than horses? 2:32
You need to sign up for Treehouse in order to download course files.Sign up