Adding a Second Activity1:57 with Ben Jakuben
Everything we've done thus far has been in the context of a single activity. This is fine for lots of apps, but sooner or later we're going to want to add more than one screen. Let's see how!
Everything we've done thus far in our course has been in the context 0:00 of a single activity. 0:03 This is fine for a lot of apps, but sooner or later, 0:04 we're going to want to add more than one screen. 0:06 Well, really soon, now, to be exact. 0:09 Currently our app has one activity and one layout file associated with it. 0:12 Let's add another one, and we'll see how to get to it from our main activity. 0:16 We want to make sure that we add the new activity in the same package 0:20 as our main activity. 0:23 So right=click on the package here, then select New and then down here we 0:24 can select Activity, and from the right we want this to be a new Empty Activity. 0:29 For the name, 0:35 let's call this StoryActivity because this will display the actual story. 0:36 If we leave this checked, we'll get a new Layout File. 0:42 We do not want this to be the Launcher Activity. 0:44 Our main activity is the Launcher Activity, 0:46 meaning that it's what's launched when the app first loads. 0:48 We do want Backwards Compatibility checked so we can use the AppCompat activity, 0:51 and we've already selected the correct package here, so we can click Finish. 0:55 All right, easy enough. 1:01 We'll set the layout in a little while. 1:02 But first things first, let's figure out how to navigate here from our main 1:03 activity when we tap on that button. 1:07 So let's go back to our MainActivity file. 1:10 And right now we are just toasting the name. 1:13 We can go ahead and delete this line. 1:14 But we do want to keep the code that sets the name variable as we're going 1:18 to want that. 1:21 Now we could just start our new activity right here, but 1:22 instead let's put it inside of a new method. 1:24 This will make things a little bit easier to understand. 1:26 Let's just type a method and we'll create it with a quick fix, startStory() and 1:29 now if we click on it and hit Alt+Enter, we can create the new method. 1:35 And we want to create it inside MainActivity, 1:40 not inside our anonymous inner class. 1:42 That creates it down here as a private void method. 1:44 And inside here, we want to start our new activity using an important Android object 1:47 known as an intent. 1:52 Let's talk about intents for a minute before we write the code we need. 1:54
You need to sign up for Treehouse in order to download course files.Sign up