Sunteți pe pagina 1din 35

Tell us what you think and win prizes in the Tuts+ Annual Survey 2014.

Dismiss

All Topics Find tutorials, courses, and more...

Code Categories Learning Guides

ANDROID SDK

Create a Hangman Game:


User Interface
by Sue Smith 10 Feb 2014
5 Comments

6 16 2

This post is part of a series called Create a Hangman Game for Android.

Create a Hangman Game: User Interaction


open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
In this series, we are creating a Hangman game for the Android platform. In the first
tutorial, we set the application up to present two screens to the user and we also
made a start with the user interface elements, the images and shape drawables to
be precise. In the second tutorial, we will zoom in on the game's layout.

Introduction
Creating the game's layout will involve using an adapter to create letter buttons and
positioning the body parts we will display when users select incorrect letters. We will
also store the player's answers in XML, retrieve them, and choose a random word
using Java.

To refresh your memory, this is what the final game will look like.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1. Position the Body Parts

Step 1
In the previous tutorial, we created images for the gallows and for the six body
parts. We will place these inside the game's layout in this tutorial. The positions you
set for these elements need to be determined by the image elements that you are
using. One approach is to import the images into a image editor, such as Adobe's
Photoshop, position them manually, and then use their x and y positions relative
to the gallows image to work out the correct positions to apply to each image in the
XML layout. If you are starting with the demo images we included in the previous
tutorial, you can use the values listed in this tutorial.

Start by opening activity_game.xml. Inside the linear layout that we added in the
previous tutorial, enter a relative layout to hold the seven images that will make up
the gallows area.

1 <RelativeLayout
2 android:layout_width
="fill_parent"

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2 android:layout_width="fill_parent"
3 android:layout_height="wrap_content"
4 android:background="#FFFFFFFF"
5 android:gravity="center"
6 android:paddingTop="15dp" >
7 </RelativeLayout>

Step 2
Inside the relative layout you just created, start by adding the gallows image as
shown below.

1 <ImageView
2 android:layout_width="wrap_content"
3 android:layout_height="wrap_content"
4 android:contentDescription="@string/gallows"
5 android:paddingLeft="0dp"
6 android:paddingTop="0dp"
7 android:src="@drawable/android_hangman_gallows"/>

Remember to modify the drawable name if the image you're using is named
differently. We set the image's left and top padding to 0 so that we can position the
other images relative to its position. We'll add string resources for the content
descriptions a bit later in this tutorial. Next up is the head.

1 <ImageView
2 android:id="@+id/head"
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2 android:id="@+id/head"
3 android:layout_width="wrap_content"
4 android:layout_height="wrap_content"
5 android:contentDescription="@string/head"
6 android:paddingLeft="108dp"
7 android:paddingTop="23dp"
8 android:src="@drawable/android_hangman_head"/>

If you're using your own images, you'll need to alter the left and top padding
accordingly. We use an id attribute so that we can refer to the image in code. This
is necessary to make it appear and disappear depending on the user's input. The
next image we add is the body.

1 <ImageView
2 android:id="@+id/body"
3 android:layout_width="wrap_content"
4 android:layout_height="wrap_content"
5 android:contentDescription="@string/body"
6 android:paddingLeft="120dp"
7 android:paddingTop="53dp"
8 android:src="@drawable/android_hangman_body"/>

This looks very similar to what we did for the head and, as you can see below, the
arms and legs are pretty similar.

01 <ImageView
02 android:id="@+id/arm1"

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
02 android:id="@+id/arm1"
03 android:layout_width="wrap_content"
04 android:layout_height="wrap_content"
05 android:contentDescription="@string/arm"
06 android:paddingLeft="100dp"
07 android:paddingTop="60dp"
08 android:src="@drawable/android_hangman_arm1"/>
09
10 <ImageView
11 android:id="@+id/arm2"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:contentDescription="@string/arm"
15 android:paddingLeft="120dp"
16 android:paddingTop="60dp"
17 android:src="@drawable/android_hangman_arm2"/>

01 <ImageView
02 android:id="@+id/leg1"
03 android:layout_width="wrap_content"
04 android:layout_height="wrap_content"
05 android:contentDescription="@string/leg"
06 android:paddingLeft="101dp"
07 android:paddingTop="90dp"
08 android:src="@drawable/android_hangman_leg1"/>
09
10 <ImageView
11 android:id="@+id/leg2"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:contentDescription="@string/leg"
15 android:paddingLeft="121dp"

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
15 android:paddingLeft="121dp"
16 android:paddingTop="90dp"
17 android:src="@drawable/android_hangman_leg2"/>

Open the project's res/values strings XML file and add the content description
strings that we've used in the above code snippets.

1 <string name="gallows">The Gallows</string>


2 <string name="head">The Head</string>
3 <string name="body">The Body</string>
4 <string name="arm">An Arm</string>
5 <string name="leg">A Leg</string>

Go back to the layout file and switch to theGraphical Layout tab to see the result
of our work. Adjust the top and left padding of each image to adjust their position if
necessary.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Whenever a new game is started, the body parts need to be hidden. Each body part
is revealed if the player chooses a letter that is not present in the target word.

2. Store the Answer Words


The game will use a collection of predefined words, which we will store in XML. In
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
your project resources values folder, add a new file and name it arrays.xml.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Switch to the XML tab, create an array, and add a few words to it.

01 <resources>
02 <string-array name="words">
03 <item>CHARGER</item>
04 <item>COMPUTER</item>
05 <item>TABLET</item>
06 <item>SYSTEM</item>
07 <item>APPLICATION</item>
08 <item>INTERNET</item>
09 <item>STYLUS</item>
10 <item>ANDROID</item>
11 <item>KEYBOARD</item>
12 <item>SMARTPHONE</item>
13 </string-array>
14 </resources>

For this tutorial, we use one array of words related to computing. However, to make
the game more interesting, you could work with various categories with each
category containing words related to a specific theme. When the user clicks the
play button, you could prompt them to choose a category and read in the relevant
array of words.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
3. Choose and Present a Word

Step 1
Back in your game's activity layout file, add a linear layout immediately after the
relative layout we added for the gallows area. The linear layout is reserved for the
answer area.

01 <LinearLayout
02 android:id="@+id/word"
03 android:layout_width="fill_parent"
04 android:layout_height="wrap_content"
05 android:layout_marginBottom="5dp"
06 android:background="#FFFFFFFF"
07 android:gravity="center"
08 android:orientation="horizontal"
09 android:padding="10dp" >
10 </LinearLayout>

We store each character of the target word within its own text view so that we can
reveal each letter separately. We will use the id of the linear layout in code to add
the text views each time a new word is chosen.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Step 2
Open the GameActivity class and start by adding the following import statements
at the top.

1 import android.content.res.Resources;
2 import android.graphics.Color;
3 import android.view.Gravity;
4 import android.view.ViewGroup.LayoutParams;
5 import android.widget.LinearLayout;
6 import android.widget.TextView;

Inside the class declaration, add an onCreate method as shown below.

1 @Override
2 protected void onCreate(Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.activity_game);
5 }

We set the content view to the layout file we created a moment ago.

Step 3
Before we move on, we need to declare a few instance variables. Add the
declaration immediately before the onCreate method.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 private String[] words;
2 private Random rand;
3 private String currWord;
4 private LinearLayout wordLayout;
5 private TextView[] charViews;

The collection of words are stored in an array and the application uses the rand
object to select a word from the array each time the user starts a new game. We
keep a reference to the current word ( currWord ), the layout we created to hold the
answer area ( wordLayout ), and an array of text views for the letters ( charViews ).
Back in onCreate , after setting the content view, request the application's
resources, read the collection of words, and store them into the words instance
variable.

1 Resources res = getResources();


2 words = res.getStringArray(R.array.words);

Note that we use the name we gave the word array in XML. Initialize the rand
object and currWord string.

1 rand = new Random();


2 currWord = "";

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Get a reference to the layout area we created for the answer letters.

1 wordLayout = (LinearLayout)findViewById(R.id.word);

Step 4
A number of tasks need to be performed every time a new game is started by the
player. Let's create a helper method to keep everything organized. After the
onCreate method, add the following method outline.

1 private void playGame() {


2 //play a new game
3 }

Inside the playGame method, start by choosing a random word from the array.

1 String newWord = words[rand.nextInt(words.length)];

Because the playGame method is invoked when the user chooses to play again
after winning or losing a game, it is important that we make sure we don't pick the
same word two times in a row.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 while(newWord.equals(currWord)) newWord = words[rand.nextInt(words.length)];

Update the currWord instance variable with the new target word.

1 currWord = newWord;

Step 5
The next step is to create one text view for each letter of the target word. Still inside
our helper method, create a new array to store the text views for the letters of the
target word.

1 charViews = new TextView[currWord.length()];

Next, remove any text views from the wordLayout layout.

1 wordLayout.removeAllViews();

Use a simple for loop to iterate over each letter of the answer, create a text view
for each letter, and set the text view's text to the current letter.

1 for (int c = 0; c < currWord.length(); c++) {


open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 for (int c = 0; c < currWord.length(); c++) {
2 charViews[c] = new TextView(this);
3 charViews[c].setText(""+currWord.charAt(c));
4 }

The string is stored as an array of characters. The charAt method allows us to


access the characters at a specific index. Still inside the for loop, set the display
properties on the text view and add it to the layout.

01 for (int c = 0; c < currWord.length(); c++) {


02 charViews[c] = new TextView(this);
03 charViews[c].setText(""+currWord.charAt(c));
04
05 charViews[c].setLayoutParams(
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutPar
06 charViews[c].setGravity(Gravity.CENTER);
07 charViews[c].setTextColor(Color.WHITE);
08 charViews[c].setBackgroundResource(R.drawable.letter_bg);
09 //add to layout
10 wordLayout.addView(charViews[c]);
11 }

We set the text color to white so that the user will not be able to see it against the
white background. If they guess the letter correctly, the text color property is se to
black to reveal it to the player. Back in the onCreate method, call the helper
method we just created.

1 playGame();
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
playGame();

We'll expand both the onCreate and the helper method a bit later.

4. Create the Letter Buttons

Step 1
The next step is to create an area for the player to choose letters to guess. Revisit
the game's activity layout and add the following grid view to hold the letter buttons.
Insert the grid view immediately after the linear layout we added for the answer
word.

01 <GridView
02 android:id="@+id/letters"
03 android:layout_width="fill_parent"
04 android:layout_height="wrap_content"
05 android:layout_gravity="center"
06 android:layout_marginBottom="5dp"
07 android:background="#FF000000"
08 android:horizontalSpacing="5dp"
09 android:numColumns="7"
10 android:padding="5dp"
11 android:stretchMode="columnWidth"
12 android:verticalSpacing="5dp" />

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
We're going to use an adapter to map the letters of the alphabet to buttons in the
grid view. We lay out seven buttons per row as you can see from the numColumns
attribute.

Step 2
Each letter is going to be a button added to the layout using an adapter. Add a new
file in your project layout folder, name it letter.xml, and populate it with the following
code snippet.

1 <Button xmlns:android="http://schemas.android.com/apk/res/android
"
2 android:layout_width="wrap_content"
3 android:layout_height="35dp"
4 android:background="@drawable/letter_up"
5 android:onClick="letterPressed" />

We use one of the drawable shapes we created last time as background and set an
onClick method we will implement next time. If you are enhancing the application
to target different screen densities, you can consider tailoring the height attribute
accordingly.

Step 3
Add a new class to your project's src package, name it LetterAdapter, and
choose android.widget.BaseAdapteras its superclass.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
As you'll see, an adapter class includes a series of standard methods we will
implement. Add the following import statements to the new class.

1 import android.content.Context;
2 import android.view.LayoutInflater;
3 import android.widget.Button;

Inside the class declaration, add two instance variables as shown below.

1 private String[] letters;


2 private LayoutInflater letterInf;

The letters array will store the letters of the alphabet and the layout inflater will
apply the button layout we defined to each view handled by the adapter. After the
instance variables, add a constructor method for the adapter.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 public LetterAdapter(Context c) {
2 //setup adapter
3 }

Inside the constructor, instantiate the alphabet array and assign the letters A-Z to
each position.

1 letters=new String[26];
2 for (int a = 0; a < letters.length; a++) {
3 letters[a] = "" + (char)(a+'A');
4 }

Each character is represented as a number so that we can set the letters A to Z in a


loop starting at zero by adding the value of the character A to each array index. Still
inside the constructor method, specify the context in which we want to inflate the
layout, which will be passed from the main activity later.

1 letterInf = LayoutInflater.from(c);

Eclipse should have created a getCount method outline. Update its implementation
as follows.

1 @Override
2 public int getCount() {
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2 public int getCount() {
3 return letters.length;
4 }

This represents the number of views, one for each letter. We don't call the methods
in the adapter class explicitly within the application. It's the operating system that
uses them to build the user interface element we apply the adapter to, which in this
case will be the grid view.

Update the implementation of getView as shown in the code snippet below.

01 @Override
02 public View getView(int position, View convertView, ViewGroup parent) {
03 //create a button for the letter at this position in the alphabet
04 Button letterBtn;
05 if (convertView == null) {
06 //inflate the button layout
07 letterBtn = (Button)letterInf.inflate(R.layout.letter, parent,
false
08 } else {
09 letterBtn = (Button) convertView;
10 }
11 //set the text to this letter
12 letterBtn.setText(letters[position]);
13 return letterBtn;
14 }

Take a moment to let everything sink in. Essentially, this method builds each view
mapped to the user interface element through the adapter. We inflate the button
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
layout we created and set the letter according to the position in the alphabet that the
view represents. We have stated that there will be 26 views being mapped, with the
position of each reflecting its position in the alphabet array. You can leave the other
methods in the adapter class as they are.

1 @Override
2 public Object getItem(int arg0) {
3 return null;
4 }
5
6 @Override
7 public long getItemId(int arg0) {
8 return 0;
9 }

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement

Step 4
Revisit the game's activity class and add an instance variable for the grid view and
the adapter.

1 private GridView letters;


2 private LetterAdapter ltrAdapt;

You also need to add another import statement.

1 import android.widget.GridView;
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
In the onCreate method, before the line in which you call the playGame helper
method, get a reference to the grid view.

1 letters = (GridView)findViewById(R.id.letters);

Append the playGame 's current implementation with the following snippet. In this
snippet, we instantiate the adapter and set it on the grid view.

1 ltrAdapt=new LetterAdapter(this);
2 letters.setAdapter(ltrAdapt);

Run the application in the emulator and you should see the user interface.
However, you won't be able to interact with the buttons yet. That's what we will
focus on in the third and final installment of this series.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Conclusion
If you run your application at this point, it will present you with the game's interface,
but it won't respond to user interaction yet. We will implement the remaining
functionality in the final part of this series.
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
When a player clicks the letter buttons, the application needs to verify if the selected
letter is included in the target word and update the answer and gallows accordingly.
We will also present a dialog to the player if they win or lose, and we'll also add a
help button. Finally, we'll add basic navigation through an action bar.

Advertisement

Difficulty: Suggested Tuts+ Course


Intermediate
Length:
Medium
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Medium
Categories:

Android SDK Mobile Development

Translations Available:

Tuts+ tutorials are translated by our community


members. If you'd like to translate this post into
Multi-Platform Apps In C# With Start
another language, let us know! Xamarin

Download Attachment
Related Tutorials

Create a Weather App on Android


Code

About Sue Smith


I'm a technical writer and sometimes
developer, based in the UK. Producing
An Introduction to Android
educational material and documentation, I Transitions
cover mobile, Web and software development Code
topics.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Build A Custom Launcher on Android
Code

Jobs

WordPress Developer
at WebDevStudios in Los Angeles, CA,
USA

Front-End WordPress Designer


Advertisement
at WebDevStudios in Los Angeles, CA,
USA

Envato Market Item

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
5 Comments Mobiletuts+

Sort by Best

Join the discussion

Vinay Vanama 5 months ago


Thanks for your Tutorial
please say me how to print the "_" in the place of word when launching the activity...
Reply Share

Johan 9 months ago


Thank you for a brilliant tutorial!

I do have one question that I would be very grateful if you could answer. Im trying to add some swedish wo
version of this hangman game. However that demands the use of the letters ", , ".

And im not really sure how to add those letters to the buttons.

I have tried messing around with the code but I just cant seem to provide button 27,28 and 29 with , ,
those buttons get the symbols [, \, ]. when i expand the button number to 29 instead of 26.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
This might be a stupid question and something I should have been able to figure out but I just cant seem t
therefore I would greatly appreciate any help I could get with this.

Regards

Johan
Reply Share

Shum 10 months ago


Hey ! !
First of all, bow bow bow to you for such a great explanation.Thank you for putting such great efforts.
I am making an android game app a bit similar to your tutorial.
Waiting for the last part of the series. Please get some time and complete the tutorial. Waiting eagerly.
Reply Share

Latest Tutorials 10 months ago


great work... During mine studies in university in the course of "Multimedia Application development" cours
that game using Action Scripting.
Reply Share

JP 10 months ago
Nice tutorial, when will the next part come out?
Reply Share

Subscribe d Add Disqus to your site Privacy

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement

18,724 Tutorials 447 Video Courses


Teaching skills to millions worldwide.

Follow Us Email Newsletters


open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Follow Us Email Newsletters

Get Tuts+ updates, news, surveys &


offers.

Help and Support Email Address

FAQ
Subscribe
Terms of Use
Contact Support Privacy Policy
About Tuts+
Advertise
Teach at Tuts+

Custom digital services like logo design, WordPress installation, video


production and more.
Check out Envato Studio

Add more features to your website such as user profiles, payment


gateways, image galleries and more.
Browse WordPress Plugins

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2014 Envato Pty Ltd. Trademarks and brands are the property of their respective
owners.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com

S-ar putea să vă placă și