Daily Word App — Android #6

do we like the Peach color?

Finally! About 6 days after the iOS version it’s here! It’s time to put what we’ve learned so far into action and build a little app that actually does something semi-useful. We’re going to make an app that will show an amazing new word every time you open the app … not the most awesome idea you’ve ever heard but it will allow us to do a few things that you’ll use in the future:

  • Store information in variables and arrays.
  • Display and change information on screen.
  • Carry out actions when users tap on buttons.
  • Use images that we import into the app.
  • Write some basic logic — by making choices using if statements.

and more! For info, there’s an iOS version of this tutorial here.

Design first

Always have an idea of what the app will look like before you start coding. Here’s the end result of what we’re building, taken directly as a screenshot from the Android Studio design tool:

Not the most graphically amazing of apps, but it’ll do for this tutorial.

Design also means UX

Design is not just how it looks, but how the user uses it (UX — user experience), so we also need to define at the design stage how it’s going to work:

  • When the app is opened, a word will appear on screen e.g. Féileacáin above (the Irish for butterfly, just a beautiful word!)
  • When the user hits Go, the word will change.
  • When the user hits any of the Irish, English or French buttons, the word will change to that language and the next time the Go button is tapped, the new word will be in that language.

Create a new project in Android Studio

Let’s get started! Open Android Studio and hit Start a new Android project

Give it an Application name and something like whatever.example.com in Company Domain (not important for now) and select a Project location:

Select the defaults on the next dialog:

Select an Empty Activity:

Choose a name for your Activity — or just leave it as MainActivity:

and hit Finish.

The project will begin to open; you’ll see messages like this as it does so:

Then, it should open up fully:

Note that there may be red text and lines for a minute or so — this doesn’t mean anything’s wrong, the project has just not completed opening yet, so hang on until all that red disappears.

Build the UI

First thing we’ll do is create our user interface — what the user will see on screen. It’s a simple app with only one screen, so won’t take too long.

In the project explorer in the left-hand panel, open the app->res->layout folder and double-click on the activity_main.xml file to open it:

and you’ll see:

This is, of course, where you can design the User Interface (UI) of Activities — what they look like, what elements are “on screen” etc. By default the Activity comes with a RelativeLayout object, which is used here as the parent object defining how all other objects will be laid out, and also a TextView that says “Hello World!”. (it’s a tradition in programming that first apps always say Hello World).

We’ll change that TextView to say “Daily Word” and we’ll change it to a bigger font size, along with changing it’s width and colors. Select it by clicking on it in the Component Tree:

On the right-hand Properties panel, change layout_width from wrap_content to match_parent:

changing layout_width

This makes the object the same width as its parent object (what it is inside). In this case, that’s the main RelativeLayout object, which is the almost the width of the screen, so this results in:

Cool. Now let’s change the “Hello World” text to “Daily Word” — do this in Properties (making sure the TextView is still selected):

changing the text in Properties

Now, let’s centre the text, by using the centre textAlignment button:

and also increase the font-size, using the textSize property:

This should result in this:

We can also change the text color, via the textColor property. Click just to the right of the textColor box:

and this should appear:

On the left-hand side, click Color — and then you can pick what color you want the text to be:

which should result it:

For interest, hit the Text tab at the bottom of the Design Tool to see the XML code for this TextView:

XML for TextView

or if you want to copy / paste at some stage:

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Daily Word"
android:textAlignment="center"
android:textSize="30sp"
android:textColor="@android:color/holo_green_light"
/>

Note that there’s a line of XML code for each of the properties that we changed using the Properties panel e.g.

android:textSize="30sp"

to change the font size. It’s easier for now to change properties using the Properties panel, and to ignore the XML, but it’s still worth being aware of it, because it may be easier at a later stage to make changes to theXML e.g. if you want copy an object and use the code elsewhere.

Ok, back to the app, that’s just one object, lots more to do!

We have to add:

  • A TextView to show the “Daily Word”
  • A Button to allow the user to see a new word
  • Three more Buttons to allow the user to switch language to Irish, English or French.

Before we add all of those, we’ll add a LinearLayout (vertical) so we can layout the objects to match our design. Drag one out from the Palette and put it in the Component Tree, below the RelativeLayout. Then drag the existing “Daily Word” TextView into the LinearLayout:

Now add another TextView, to display the actual daily word, put it under the other TextView:

and the Activity will look like this:

Let’s change the new TextView’s properties. Centre Align it and jack up the size, so it looks like this:

One more thing — change the ID property to “wordView”. You can change the ID to anything you want, but it’s good practice to call it something meaningful, that easily conveys what it’s for. IDs are used to link the objects in the layout file we’re currently creating with the matching Java code file.

You’ll see that once you change an Object’s ID, the name will update in the Component Tree:

Next, we’re going to add an ImageButton — this is a Button that you can set to show an image instead of a word:

But first, we need to add an image that it will use. Find one you like (I get a lot of my icons from http://icons8.com) and copy and paste it into the res->drawable folder. So copy it in Finder (Mac) / Windows Explorer and right-click on the drawable folder and select paste:

It’ll show you a dialog like this, just hit OK:

You should then see the file in the Project:

Some tips for images in Android Studio:

  • Image name should be all lowercase and can be alphanumeric or an underscore i.e. a-z , 0–9 or _
  • Don’t have any hyphens ( — ) or spaces.
  • Image name can’t start with a number.

So good names:

  • gobutton.png
  • my_gobutton.png

and some bad names that won’t work:

  • Gobutton.png
  • 1button.png

There’s a whole lot more stuff you’ll need to know about images — like how to handle different size screens / screens with different resolutions, but that’s a whole tutorial in itself. Here’s a guide by someone else with a bit more info for now.

Ok! Let’s finally drag out that ImageButton, into our LinearLayout. When we place it, this box will pop up, letting you pick an image. Pick yours and hit OK:

Our Component Tree should now look like this:

and the Activity should look like this:

We don’t want that grey background, so select the ImageView, then in Background in Propeties, start to type “Transparent” and you’ll get the option to select android/color:transparent. Click on it to select it, then hit Enter to affect the change.

The ImageButton should change to:

Happy days. Ok, now we need to add our three language buttons. How do we get them in a nice row altogether? We use another LinearLayout, this time horizontal. We place it inside our existing LinearLayout (vertical). That’s the beauty of them — by combining LinearLayouts, we can have good control over where the objects are on screen. Place it as so:

Now, drag three buttons into the LinearLayout and change their text property to “Irish”, “English” and “French”, respectively:

Also change their ID properties to “buttonIrish”, “buttonEnglish” and “buttonFrench” aswell, to make it more understandable. The Component Tree will look like this:

If the three buttons aren’t all the same size and laid out nicely as above, then make sure that their layout_width property is set to wrap_content.

Button with ID, text and layout_width properties set

Ok! That’s our layout file almost done. Take a look at the XML file (by hitting the Text tab again at the bottom, the XML code should be like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.whatever.dailyirish.MainActivity"
>

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:drawable/screen_background_light_transparent"
>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Daily Word"
android:textAlignment="center"
android:textSize="30sp"
android:textColor="@android:color/holo_green_light"
/>

<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/wordView"
android:textSize="46sp"
android:textAlignment="center"
android:layout_marginTop="20dp"
/>

<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/gobutton"
android:id="@+id/imageButton"
android:layout_marginBottom="20dp"
android:onClick="onGoClick"
android:background="@android:color/transparent"
/>

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<Button
android:text="Irish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonIrish"
android:layout_weight="1"
/>

<Button
android:text="English"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonEnglish"
android:layout_weight="1"
/>

<Button
android:text="French"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonFrench"
android:layout_weight="1"
/>
</LinearLayout>

</LinearLayout>
</RelativeLayout>

When you have Buttons, you need to have a way to know when the user clicks them. This is done with the onClick property — you set it to be the name of a method in the Java file for that Activity. So here, edit the three language buttons as follows:

<Button
android:text="Irish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonIrish"
android:layout_weight="1"
android:onClick="onIrishClick"
/>

<Button
android:text="English"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonEnglish"
android:layout_weight="1"
android:onClick="onEnglishClick"
/>

<Button
android:text="French"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonFrench"
android:layout_weight="1"
android:onClick="onFrenchClick"
/>

We’ve added in:

android:onClick="onIrishClick"android:onClick="onEnglishClick"

and

android:onClick="onFrenchClick"

Note that these methods don’t exist yet, but we can still type them in. Note aswell that we could have called them anything, but “onIrishClick” is a meaningful name.

We need to add one aswell for the Go Button:

android:onClick="onGoClick"

so:

<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/gobutton"
android:id="@+id/imageButton"
android:layout_marginBottom="20dp"
android:onClick="onGoClick"
android:background="@android:color/transparent"
/>

Ok, still awake? Time to write some code. Double click on the MainActivity Java file to open it:

All that’s really there is the onCreate method. This is ran whenever the Activity is created — so if there’s anything you want to happen when the screen is first shown, you can add code to that method.

In this file we need to:

  • Create a variable to store the current language
  • Create 3 arrays to hold Irish, English and French words
  • Create a variable to store the index of the current word — i.e. which position in the arrays is the word from.
  • A method to set / change the word on screen
  • A method for when the Go button is clicked
  • Three methods — one for each language button.

So let’s get started:

After the main class declaration, create a variable to store the current language:

String language = "French";

Then create the three arrays we need, with some initial values:

String[] irishArray = new String[]{"Madra","Coinín","Féileacáin"};
String[] englishArray = new String[]{"Dog","Rabbit","Butterfly"};
String[] frenchArray = new String[]{"Chien","Lapin","Papillon"};

Then create the variable to store the array index:

int arrayIndex = 0;

We also create a “null” TextView variable:

TextView wordView = null;

This will be used later to store a reference to the TextView in the Layout file that we created to show the actual Daily Word. “null” is way of saying it doesn’t exist yet, more or less.

The code now looks like this:

Let’s now create the main method we need to set / change the word on screen. The method needs to:

  • Get a reference to the wordView TextView we created in the layout file so we can change it via code
  • Check what the current language is and based on that set the word to a random word from the relevant array

I’m calling the method setWord but as usual you can call it anything you like:

public void setWord(){
wordView = (TextView) findViewById(R.id.wordView);
Random r = new Random();
int num = r.nextInt(2 - 0);

arrayIndex = num;

String wordToUse = "";

if (language.equals("Irish")){
wordToUse = irishArray[num];
}else if (language.equals("English")){
wordToUse = englishArray[num];
} else{
wordToUse = frenchArray[num];
}

wordView.setText(wordToUse);
}

There’s a lot going on there so let’s break it down:

public void setWord(){

This declares the method and gives it a return type of void — this means it won’t be returning a value, it’ll just “do” something.

wordView = (TextView) findViewById(R.id.wordView);

Here we store in our wordView variable, the TextView we added to the layout file earlier. We get the TextView by using the method findViewByID which takes as a paramater R.id. followed by the ID of the object we want. If we remember our XML code for that TextView:

<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/wordView"
android:textSize="46sp"
android:textAlignment="center"
android:layout_marginTop="20dp"
/>

we see that the ID is wordView. (Ignore the “@+id/ bit at the start) so the full line is:

TextView wordView = (TextView) findViewById(R.id.wordView);

The

(TextView)

bit “casts” the result of findViewById to a TextView class — don’t worry too much about this, it’s basically there as the findViewById can return any object with an ID, so we’re just telling Android that it’s a TextView.

Random r = new Random();
int num = r.nextInt(2 - 0);

This creates a random number between 0 and 2 and stores it in the num variable. The 2 in the second line is the upper-range of the arrays we use. i.e. if we had an array we 10 words, then we’d have:

int num = r.nextInt(9 - 0);

The

arrayIndex = num;

sets our variable to track the index to this number; we’ll need this later if someone wants to change the language — so we’ll know what word to pick from the other language array.

String wordToUse = "";

declares an empty variable to store the word we’ll use.

if (language.equals("Irish")){
wordToUse = irishArray[num];
}else if (language.equals("English")){
wordToUse = englishArray[num];
} else{
wordToUse = frenchArray[num];
}

then checks what the language is, and based on that, sets wordToUse as the word from the correct array at the index with the random number num we just created.

i.e. if the random number is 2 then

wordToUse = irishArray[num];

will get the 3rd item in the irishArray i.e. Féileacáin

Finally, we actually change the TextView to show this word:

wordView.setText(wordToUse);

This should all look like this in Android Studio:

Let’s now add the the onGoClick method. This will just call our setWord method:

public void onGoClick(View v){
setWord();
}

Go ahead and run the app now if you want and try out the Go button — when you hit it, the word should change. Bear in mind it picks a word randomly from the array — but as there’s only 3 words in the array, it may take a few goes to select a new word!

Now we add methods for when the user hits the language buttons. These will:

  • Change the language variable
  • Set the word to that language — using the arrayIndex variable.

Basically how it all works — each time the word is changed, the arrayIndex stores the index. Because the three arrays — Irish, English and French have been created with the same order:

String[] irishArray = new String[]{"Madra","Coinín","Féileacáin"};
String[] englishArray = new String[]{"Dog","Rabbit","Butterfly"};
String[] frenchArray = new String[]{"Chien","Lapin","Papillon"};

we can then just get a word in a different language by using the index.

e.g. if the arrayIndex is 0 i.e. Madra, then we can quickly get the French version, which is the word at the index 0 — Chien. Genius.

public void onIrishClick(View v){
Button btn = (Button) findViewById(R.id.buttonIrish);
language = "Irish";
wordView.setText(irishArray[arrayIndex]);
}

public void onEnglishClick(View v){
Button btn = (Button) findViewById(R.id.buttonIrish);
language = "English";
wordView.setText(englishArray[arrayIndex]);
}

public void onFrenchClick(View v){
Button btn = (Button) findViewById(R.id.buttonIrish);
language = "French";
wordView.setText(frenchArray[arrayIndex]);
}

So, for each of the three methods:

  • we create a Button object, from the corresponding Button in the Layout file
  • Set the language appropriately
  • Set the word on screen to the same word, just the selected language.

One last thing and we’re done — in the onCreate method, call the setWord method, as we want to show a word the first time the app runs:

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

So, the final code should look something like this:

package com.example.whatever.dailyirish;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

String language = "French";

String[] irishArray = new String[]{"Madra","Coinín","Féileacáin"};
String[] englishArray = new String[]{"Dog","Rabbit","Butterfly"};
String[] frenchArray = new String[]{"Chien","Lapin","Papillon"};

int arrayIndex = 0;

TextView wordView = null;

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

public void setWord(){
wordView = (TextView) findViewById(R.id.wordView);

Random r = new Random();
int num = r.nextInt(2 - 0);

arrayIndex = num;

String wordToUse = "";

if (language.equals("Irish")){
wordToUse = irishArray[num];
}else if (language.equals("English")){
wordToUse = englishArray[num];
} else{
wordToUse = frenchArray[num];
}

wordView.setText(wordToUse);
}

public void onIrishClick(View v){
Button btn = (Button) findViewById(R.id.buttonIrish);
language = "Irish";
wordView.setText(irishArray[arrayIndex]);
}

public void onEnglishClick(View v){
Button btn = (Button) findViewById(R.id.buttonIrish);
language = "English";
wordView.setText(englishArray[arrayIndex]);
}

public void onFrenchClick(View v){
Button btn = (Button) findViewById(R.id.buttonIrish);
language = "French";
wordView.setText(frenchArray[arrayIndex]);
}

public void onGoClick(View v){
setWord();
}

}

One note — the import commands at the start:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

are needed to include the Classes of some of the objects you use, like Button and TextView. You can set Android Studio to import these automatically, by going to Preferences (Mac) or Settings (Windows) and going to Editor->General->Auto Import and ticking Optimize imports on the fly and Add unambiguous imports on the fly.

Ok, run the app and try it out! Any issues, comment below!

If you found this useful, feel free to hit the little heart recommend button below, so others can find it too! Thanks, Andy.

--

--

--

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Case Study: Drive a Senior Northwest Redesign

Boardgames for Team Building: Building Monopoly in Vulcan

Landing a Man on the Moon

Screenshots for App Store

What are various methods to select a SoftMattress? https://t.co/ggodxReNF1

Hello, Runner Pro!

UX Case Study | Local E-Commerce

Dunbar Old Books E-Commerce Website Redesign

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andy O'Sullivan

Andy O'Sullivan

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188

More from Medium

My project.first.kt #1

Steps to setup firebase database to your Android project.

Building a Simple calculator App in android studio.

Shortcuts in Android