You are on page 1of 17

Building Interactive Apps

The App Structure


1. The layout defines the appearance of the app.

2. The string resources required by the layout are listed in the strings.xml file.

3. The activity determines how the app interacts with the user.

4. The Custom Java class defines the application logic.

Step #1 - Create a Project


Since we are creating a brand-new app, we will need to create a new project.

And like before, we have to create a basic layout and activity.

Step #2 - Update the Layout


Once we have a basic app set up, we need to amend the layout so that it includes
all the GUI components the app needs.

 We will explore two different types of Android layouts in this course - Linear
layouts and relative layouts.

Step #3 - Wire the Layout to the Activity


The layout creates visuals. To get the app up and running, we need to wire the layout to
the Java code in our activity

Step #4 - Write the Application Logic


And finally, we will add a Java custom class to the app, and use it to store and retrieve
weird words and their meanings on the tap of a button.

An app developer is someone who can write code that an Android device
understands.
A GOOD app developer is someone who can write code that a human
understands.

There are a few concepts that you need to be familiar with before we start
building the application.
These include: Views are the basic building blocks for the elements of the User
Interface.
A View fills a rectangular area on the screen and is responsible for drawing and
event handling.
All Views inherit from View class (android.view.View)
Listed as follows are some of the common View subclasses which will be used in
Android applications:

 TextView
 EditText
 Button
 CheckBox
 RadioButton
 ImageButton
 Progress Bar
 Spinner

Android Layouts
Android Views
Android ViewGroups

Android Layouts
Layouts are typically defined in XML and can include GUI components such as text fields,
buttons, and labels.

Android Views
Views are the basic building blocks for the elements of the User Interface.
A View fills a rectangular area on the screen and is responsible for drawing and
event handling.
All Views inherit from View class (android.view.View)
Listed as follows are some of the common View subclasses which will be used in
Android applications:

 TextView
 EditText
 Button
 CheckBox
 RadioButton
 ImageButton
 Progress Bar
 Spinner

The ViewGroup subclass is the base class for layouts, which are invisible


containers that hold other Views (or other ViewGroups) and define their layout
properties.

 The ViewGroup is a subclass of View.

The following are the commonly used ViewGroup subclasses in Android


applications:

 Linear Layout
 Relative Layout
 Table Layout
 Frame Layout
 Web View
 List View
 Grid View

Both View and ViewGroup subclasses together will play a key role in creating
layouts in Android applications.

The Layout Editor - How's the View?


The Android Studio encompasses a layout editor that facilitates the quick
designing of an app's layout of User Interface (UI) elements.
With the help of the layout editor, UI elements can be added to a visual
design/blueprint view and positioned in the layout. It also facilitates adding
constraints and setting attributes to the elements.
 Constraints are used to control the position of a UI element within the layout.

Get familiarized with the layout editor by referring to the image and the numbered
steps in the upcoming cards.

The Layout Editor - Dissected

1. Open activity_main.xml from app > res > layout folder in the Project >


Android pane (if it is not open already).
2. Click the Design tab to open the design editor.
o The design tab can be used to manipulate the layout and the UI elements,
while the text tab can be used to manipulate the XML code for the layout.
3. The Palettes pane shows UI elements that will be used in the app's layout.
4. The Component tree pane depicts the view hierarchy of the UI elements.
o View elements are organized into a tree hierarchy of parents and
children, in which a child inherits the attributes of its parent.
o In the image above, the TextView is a child of
the ConstraintLayout.
5. The design and blueprint panes of the layout editor help visualize the UI
elements in the layout.
o In the image above, the layout shows only one element: a TextView
that displays "Hello World".
6. The Attributes tab launches the Attributes pane for setting the properties
of the UI elements.

What Did I Just Do?


You just changed the code Android Studio generated so that it uses
a <LinearLayout>.
This is used to display GUI components next to each other, either vertically or
horizontally.

 If it is vertical, they are displayed in a single column, and if it is horizontal, they are
displayed in a single row.

android:background="#E91E63" sets a background color to the layout.

android:gravity specifies how an object should position its content on both X


and Y-axis.

Any change made to a layout's XML is reflected in the Android Studio's design
editor, which can be visualized by clicking the Design tab.

A button in Androidology is a pushbutton that the user can press to trigger an action.
Buttons and text views are subclasses of the same Android View class.

Few Scenarios
Hardcoding makes localization hard

Suppose you have created an app that is a huge success on your local Google
Play Store.
 You now want to make it available internationally in different languages.
 But you have hardcoded the text in your layout files!
Making the app international would be extremely difficult and would require
extensive reprogramming.
Hardcoding makes making global changes to the text harder

Suppose your company's name has been changed, and your boss has asked you
to change the wordings in your app.

 If you have hardcoded the entire text, you will need to edit a whole host of files to
change the text.

So, what can be done?

The Solution

Put the string values in strings.xml rather than hardcoding them.


strings.xml is a resource file used to hold name/value pairs of strings.

How does it help?


It is much easier to internationalize an app with the help of a string resource file.

 You can easily replace the string.xml file with an internationalized version


instead of having to edit the hardcoded text values in a whole host of numerous
layout and activity files.

It also enhances the process of making global changes to the text across the
application much efficient as you only need to edit a single file - strings.xml.
Android is available in around 46 languages, thus enabling the development of
applications in various languages to reach a wider audience.

Using String Resources


In order to use a string resource in your layout, there are two things you need to
do:
1. Create the string resource by adding it to strings.xml.
2. Use the string resource in your layout.
String Resource Creation

We are going to create 4 string resources, one for the text that appears at the
button, and three for the text that appears in the text view.

To do this, use Android Studio's explorer to find the file strings.xml in the app >
src > main > res > values folder.

The file should look similar to the following.

<resources>
<string name="app_name">WTWW</string>
</resources>

strings.xml contains a string resource named "app_name," which has a value of


WTWW.
Android Studio creates the string resource automatically every time a new project
is created.

Let's use it...


String resources can be used in your layout as follows:

android:text="@string/app_label"

As you already know, android:text specifies the text that is to be displayed.


But what does  "@string/app_label" mean?

 Let's start with the first part, @string.


o @string tells Android to look up a text value from the string resource file.
o In our case, this is the file strings.xml that you just edited.
 The second part is app_label.
o It tells Android to look up the value of a resource with the name app_label.
o So "@string/app_label" means "look up the string resource with the
name app_label, and substitute app_label the associated text value."

Here's a quick recap of what has been done so far.

1. We've created a layout that defines what the app looks like.
o It includes 3 text views and a button.
2. The file strings.xml includes the string resources needed by the
application.
o We've added a label for the button and default text for the text views
Quiz 1
The Activity Code: A Sneak Peak
When you create a new project, the wizard creates an empty activity
called MainActivity. The code for this activity is held in a file
called MainActivity.java.
Open this file from app > src > main > java folder.
You can see that Android Studio has generated Java code as follows.

MainActivity.java Deciphered
All activities (not just this one) must extend the Activity class or one of its
subclasses.
The Activity class consists of a bunch of methods that enhance your Java class
from a plain old Java class into a full-fledged, card-carrying Android activity.
All activities should also implement the onCreate() method.

 This method gets called when an object of the activity is created. It is used to
perform basic setup, such as what layout the activity is associated with.

Bundle savedInstanceState - saves the state of the activity.

setContentView() - tells the activity which layout file to use for the screen. It
parses the layout and creates a view hierarchy.
R.layout.activity_main - is the reference ID of the layout
resource activitymain.xml.

 In the previous code, setContentView(R.layout.activity_main) tells Android


that this activity uses activity_main as its layout.
Step #1: Referencing a View
The first step to display the initial weird word is to create references for the text
views.
We can get references for our GUI components using a method
called findViewById().
This method takes the ID of the GUI component as a parameter and returns a View
object.
Here is how you should use findViewById() to get a reference to the text view
with an ID my_textView:

TextView myTextView = findViewById(R.id.my_textView);

Similarly, to get a reference to a button with an ID my_button:

Button myButton = findViewById(R.id.my_button);

Wait... What's that "R"?


Take a closer look at how the ID of the text view was specified.
Instead of passing in the name of the text view, we passed in an ID of the
form R.id.wordNameView.
So what does this mean? What's R?
 R.java is a special Java file that gets generated by the Android Studio
whenever you create or build your app.
 It can be found in the app > build > generated > source > r > debug
folder in a package with the same name as the package of your app.
 Android uses R.java to keep track of the resources used within the app,
and it enables you to get references to GUI components from within your
activity code.

R.java gets generated for you.

You never change any of the code within this file, but it's useful to know it's there.

Step #2: Setting Text in the Text Views


The findViewById() method provides you a Java version of your GUI
component.
This means that you can get and set properties in the GUI component using the
methods exposed by the Java class.
Let us take a closer look.
Once you have referenced the text views, you can then call methods on the
TextView objects.
For example, say, you want to set the text in my_textView to "Hello World."
The TextView class includes a method called setText() that you can use to
change the text property.
It can be used as:

myTextView.setText("HelloWorld");

Hint: Access the wordNameView and wordMeaningView in onCreate() method


of ActivityMain.java and set their initial values.

The Button
Typically, whenever a layout includes a button, something is expected to happen
when a user clicks the button.
Buttons carry out the expected tasks by calling a corresponding method in the
activity.
In our app, to get the button to call a method in the activity when it is clicked, we
need to make changes to two files:
1. Change the layout file activity_main.xml.
o Specify the method in the activity that will be called when the button is clicked.
2. Change the activity file MainActivity.java.
o Define the method that gets called.

The onClick Attribute


It takes only one line of XML to tell Android the method a button will call when it is
clicked.
All you have to do is add an android:onClick attribute to the <button> element
and describe the name of the method that is to be called as shown as follows.
android:onClick="Method_Name"

Update Update!
Go to the layout file activity_main.xml, and add a new line of XML to the
<button> element to say that the method displayWeirdWord should be called
when the button is clicked.
Now that the layout knows which method to call in the activity, we need to define
the method.

Implementing the Method


Once the onClick attribute is added to the button, the corresponding method
should be added to the activity.
Doing so will enable the activity to respond when the user clicks the button in the
user interface.
But there is a catch!
The displayWeirdWord() method needs to have a particular signature. Otherwise,
it will not be called when the button specified in the layout gets clicked.
The method needs to take the following form.

Watch it!
To get a method to respond to a button click, it has to be made public, have
a void return type, and take a single View parameter.

The View parameter in the method may seem unusual at first, but there is a good
reason for it being there.

 This parameter refers to the GUI component that triggers the method (in this case,
the button).

Note: As mentioned earlier, GUI components such as buttons and text views are all
types of View.

Rest assured that the core functionality is working, let us remove the hard-coded
infestations from our app and organize the list of weird words in a deck.
Add a new java class - weirdWordDeck.java (in the same package as
MainActivity.java)

 To add the new class, navigate to WTWW > app > src > main > java >
com.fresco.play.wtww
 Right-click the package name, select New > Java class
 In the window that opens, name the new class as weirdWordDeck and
click ok.

Task #1 - Hints
TextView1 - WordLabelView

 The view should be aligned at the top with respect to the parent view

TextView2 - wordNameView

 The view should be above WordMeaningView


 Align the view to the left with respect to the parent view
TextView3 - WordMeaningView

 The view should be aligned in the center vertically, with respect to the
parent view.
 Assign paddings at the left, start, and top as necessary.
Button - showWordButton

 The view should be aligned at the bottom with respect to the parent view

Revisit the displayWeirdWord() method to exploit the ColorPopper class.


 Create a reference to the layout by assigning an ID to the layout in the
layout XML.
 Use the setBackgroundColor() method to assign a random background
color from the colorPopper class to the layout
 Similarly, create a reference to the button and set the button's text color with
the random color picked for the background.

Kudos mate, you are now all set to build interactive apps!
Let us look back on all that we have learned in this course:
 Got a gist of Android layouts, views, and view groups
 Mastered the Android Layout Editor
 Laid out the UI Components in both Linear and Relative layouts
 Learned to add and edit the attributes of Text views and buttons in the
layout through the layout XML as well as the design editor.
 Understood the significance of avoiding hard-coding strings and the use
of strings.xml.
 Created references for UI Components
 Set properties in the GUI component using the methods exposed by the
Java class

Points to Remember
 The Button element is used to add a button.
 The TextView element is used to add a text view.
 All GUI components are types of views. They inherit from the
Android View class.
 Strings can be referenced in the layout using "@string/string_name"
 A button can be made to call a method when clicked by adding the following
XML to the layout: android:onClick="clickMethod"
o There needs to be a corresponding method in the activity public void
clickMethod(View view) { }

Final Quiz

You might also like