New Activity

You’ll eventually want your app to include multiple screens.

One way to do that is to create additional Activity classes. Each activity represents a new screen.

Creating a new Activity:

In your Project tab, right click the folder containing your Java classes and hover over “New:”

More options appear under New.

Hover over Activity and choose an option such as Empty Activity:

[If you just click the top option, “Java Class,” you’ll have to create the activity from scratch. That’s also doable, but it’s extra work.]

Give your activity a name that indicates what the new screen is.

Capitalize the first letter, because it’s a Java class.

Notice that “Generate Layout File” is checked. This creates the XML layout file automatically.

Now you have a Java Class with code that looks something like this:

public class NewScreen extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_screen);
}
}

If you look in your “res” folder under “layouts,” you also have a new layout file that should match the name in the setContentView method call above.

In my example, the layout file is called activity_new_screen.xml.

Navigating to New Screen In App:

I want a button in my Main Activity that will launch the new screen.

This button needs a method to launch the new app. Here’s a blank method:

public void openNewScreen(View v){
    //code goes here
}

I will need to set my button’s onClick  attribute to match this method name (openNewScreen).

Intent and startActivity

An Intent is an Android object that can allow one Activity to start up another Activity.

Intent Example:

Intent intent = new Intent(this, NewScreen.class);
startActivity(intent);

The first line of code creates an Intent object named intent.
[The class name Intent (object type) is capitalized, and the name of the new object, intent, is all lower case. ]

In this example, the app has an Activity class named NewScreen that we want to open on the screen.

The second line of code starts an activity, using intent as the argument.

These lines of code go into the button’s onClick method:

public void openNewScreen(View v){
    Intent intent = new Intent(this, NewScreen.class);
    startActivity(intent);    
}