Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Tappy Defender – Building the home screen

Save for later
  • 11 min read
  • 12 Aug 2015

In this article by John Horton, the author of Android Game Programming by Example, we will look at developing the home screen UI for our game.

(For more resources related to this topic, see here.)

Creating the project

Fire up Android Studio and create a new project by following these steps.

  1. On the welcome page of Android Studio, click on Start a new Android Studio project.
  2. In the Create New Project window shown next, we need to enter some basic information about our app. These bits of information will be used by Android Studio to determine the package name.

    In the following image, you can see the Edit link where you can customize the package name if required.

  3. If you will be copy/pasting the supplied code into your project, then use C1 Tappy Defender for the Application name field and gamecodeschool.com in the Company Domain field as shown in the following screenshot:

    tappy-defender-building-home-screen-img-0

  4. Click on the Next button when you're ready. When asked to select the form factors your app will run on, we can accept the default settings (Phone and Tablet). So click on Next again.
  5. On the Add an activity to mobile dialog, just click on Blank Activity followed by the Next button.
  6. On the Choose options for your new file dialog, again we can accept the default settings because MainActivity seems like a good name for our main Activity. So click on the Finish button.

What we did

Android Studio has built the project and created a number of files, most of which you will see and edit during the course of building this game. As mentioned earlier, even if you are just copying and pasting the code, you need to go through this step because Android Studio is doing things behind the scenes to make your project work.

Building the home screen UI

The first and simplest part of your Tappy Defender game is the home screen. All you need is a neat picture with a scene about the game, a high score, and a button to start the game. The finished home screen will look a bit like this:

tappy-defender-building-home-screen-img-1

When you built the project, Android Studio opens up two files ready for you to edit. You can see them as tabs in the following Android Studio UI designer. The files (and tabs) are MainActivity.java and activity_main.xml:

tappy-defender-building-home-screen-img-2

The MainActivity.java file is the entry point to your game, and you will see this in more detail soon. The activity_main.xml file is the UI layout that your home screen will use. Now, you can go ahead and edit the activity_main.xml file, so it actually looks like your home screen should.

  1. First of all, your game will be played with the Android device in landscape mode. If you change your UI preview window to landscape, you will see your progress more accurately. Look for the button shown in the next image. It is just preceding the UI preview:

    tappy-defender-building-home-screen-img-3

  2. Click on the button shown in the preceding screenshot, and your UI preview will switch to landscape like this:
    tappy-defender-building-home-screen-img-4
  3. Make sure activity_main.xml is open by clicking on its tab.
  4. Now, you will set in a background image. You can use your own. Add your chosen image to the drawable folder of the project in Android Studio.
  5. In the Properties window of the UI designer, find and click on the background property as shown in the next image:
    tappy-defender-building-home-screen-img-5
  6. Also, in the previous image the button labelled ... is outlined. It is just to the right of the background property. Click on that ... button and browse to and select the background image file that you will be using.
  7. Next, you need a TextView widget that you will use to display the high score. Note that there is already a TextView widget on the layout. It says Hello World. You will modify this and use it for your high score. Left click on and drag the TextView to where you want it. You can copy me if you intend using the supplied background or put it where it looks best with your background.
  8. Next, in the Properties window, find and click on the id property. Enter textHighScore.
  9. You can also edit the text property to say High Score: 99999 or similar so that the TextView looks the part. However, this isn't necessary because your Java code will take care of this later.
  10. Now, you will drag a button from the widget palette as shown in the following screenshot:
    tappy-defender-building-home-screen-img-6
  11. Drag it to where it looks good on your background. You can copy me if using the supplied background or put it where it looks best with your background.

What we did

You now have a cool background with neatly arranged widgets (a TextView and a Button) for your home screen. You can add functionality via Java code to the Button widget next. Revisit the TextView for the player's high score. The important point is that both the widgets have been assigned a unique ID that you can use to reference and manipulate in your Java code.

Coding the functionality

Now, you have a simple layout for your game home screen. Now, you need to add the functionality that will allow the player to click on the Play button to start the game.

Click on the tab for the MainActivity.java file. The code that was automatically generated for us is not exactly what we need. Therefore, we will start again as it is simpler and quicker than tinkering with what is already there.

Delete the entire contents of the MainActivity.java file except the package name and enter the following code in it. Of course, your package name may be different.

package com.gamecodeschool.c1tappydefender;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity{

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //Here we set our UI layout as the view
        setContentView(R.layout.activity_main);

    }
}

The mentioned code is the current contents of your main MainActivity class and the entry point of your game, the onCreate method. The line of code that begins with setContentView... is the line that loads our UI layout from activity_main.xml to the players screen. We can run the game now and see our home screen.

Now, let's handle the Play button on our home screen. Add the two highlighted lines of the following code into the onCreate method just after the call to setContentView(). The first new line creates a new Button object and gets a reference to Button in our UI layout. The second line is the code to listen for clicks on the button.

//Here we set our UI layout as the view
setContentView(R.layout.activity_main);

// Get a reference to the button in our layout
final Button buttonPlay =
  (Button)findViewById(R.id.buttonPlay);
// Listen for clicks
buttonPlay.setOnClickListener(this);

Note that you have a few errors in your code. You can resolve these errors by holding down the Alt keyboard key and then pressing Enter. This will add an import directive for the Button class.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime

You still have one error. You need to implement an interface so that your code listens to the button clicks. Modify the MainActivity class declaration as highlighted:

public class MainActivity extends Activity 
        implements View.OnClickListener{

When you implement the onClickListener interface, you must also implement the onClick method. This is where you will handle what happens when a button is clicked. You can automatically generate the onClick method by right-clicking somewhere after the onCreate method, but within the MainActivity class, and navigating to Generate | Implement methods | onClick(v:View):void.

You also need to have Android Studio add another import directive for Android.view.View. Use the Alt | Enter keyboard combination again.

You can now scroll to near the bottom of the MainActivity class and see that Android Studio has implemented an empty onClick method for you. You should have no errors in your code at this point. Here is the onClick method:

@Override
public void onClick(View v) {
  //Our code goes here
}

As you only have one Button object and one listener, you can safely assume that any clicks on your home screen are the player pressing your Play button.

Android uses the Intent class to switch between activities. As you need to go to a new activity when the Play button is clicked, you will create a new Intent object and pass in the name of your future Activity class, GameActivity to its constructor. You can then use the Intent object to switch activities. Add the following code to the body of the onClick method:

// must be the Play button.
// Create a new Intent object
Intent i = new Intent(this, GameActivity.class);
// Start our GameActivity class via the Intent
startActivity(i);
// Now shut this activity down
finish();

Once again, you have errors in your code because you need to generate a new import directive, this time for the Intent class so use the Alt | Enter keyboard combination again. You still have one error in your code. This is because your GameActivity class does not exist yet. You will now solve this problem.

Creating GameActivity

You have seen that when the player clicks on the Play button, main activity will close and game activity will begin. Therefore, you need to create a new activity called GameActivity that will be where your game actually executes.

  1. From the main menu, navigate to File | New | Activity | Blank Activity.
  2. In the Choose options for your new file dialog, change the Activity name field to GameActivity.
  3. You can accept all the other default settings from this dialog, so click on Finish.
  4. As you did with your MainActivity class, you will code this class from scratch. Therefore, delete the entire code content from GameActivity.java.

What we did

Android Studio has generated two more files for you and done some work behind the scenes that you will investigate soon. The new files are GameActivity.java and activity_game.xml. They are both automatically opened for you in two new tabs, in the same place as the other tabs above the UI designer.

You will never need activity_game.xml because you will build a dynamically generated game view, not a static UI. Feel free to close that now or just ignore it. You will come back to the GameActivity.java file, when you start to code your game for real.

Configuring the AndroidManifest.xml file

We briefly mentioned that when we create a new project or a new activity, Android Studio does more than just creating two files for us. This is why we create new projects/activities the way we do.

One of the things going on behind the scenes is the creation and modification of the AndroidManifest.xml file in the manifests directory.

This file is required for your app to work. Also, it needs to be edited to make your app work the way you want it to. Android Studio has automatically configured the basics for you, but you will now do two more things to this file.

By editing the AndroidManifest.xml file, you will force both of your activities to run with a full screen, and you will also lock them to a landscape layout. Let's make these changes here:

  1. Open the manifests folder now, and double click on the AndroidManifest.xml file to open it in the code editor.
  2. In the AndroidManifest.xml file, find the following line of code:
    android:name=".MainActivity"
  3. Immediately following it, type or copy and paste these two lines to make MainActivity run full screen and lock it in the landscape orientation:
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:screenOrientation="landscape"
  4. In the AndroidManifest.xml file, find the following line of code:
    android:name=".GameActivity"
  5. Immediately following it, type or copy and paste these two lines to make GameActivity run full screen and lock it in the landscape orientation:
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:screenOrientation="landscape"

What you did

You have now configured both activities from your game to be full screen. This gives a much more pleasing appearance for your player. In addition, you have disabled the player's ability to affect your game by rotating their Android device.

Continue building on what you've learnt so far with Android Game Programming by Example! Learn to implement the game rules, game mechanics, and game objects such as guns, life, money; and of course, the enemy. You even get to control a spaceship!