Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Lab Exercise 02

Uploaded by

abodetl203
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lab Exercise 02

Uploaded by

abodetl203
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

BGIT 4317 | Mobile Programming Course

Lab Exercise 02
At the end of this lab you will be expected to finish the following tasks:

Task 1. Create the "Hello Toast" project

Task 2: Add views to "Hello Toast" in the Layout Editor

Task 3: Edit the "Hello Toast" Layout in XML

Task 4: Add on-click handlers for the buttons

Task 1: Create the "Hello Toast" project


 Start Android Studio and create a new project with the following parameters:

Attribute Value

Application Name Hello Toast

Company Name com.example.android or your own domain

Phone and Tablet Minimum SDK API15: Android 4.0.3 IceCreamSandwich

Template Empty Activity

Generate Layout file box Checked

Backwards Compatibility box Checked

 Select Run > Run app or click the Run icon in the toolbar to build and execute
the app on the emulator or your device.

Task 2: Add views to "Hello Toast" in the Layout


Editor
Here is a rough sketch of the UI you will build in this exercise. Simple UI sketches can be very
useful for deciding which views to use and how to arrange them, especially when your
layouts become more sophisticated.

1
BGIT 4317 | Mobile Programming Course

2.1. Change the view group to a LinearLayout


The root of the view hierarchy is a view group, which as implied by the name, is a view that
contains other views.

A vertical linear layout is one of the most common layouts. It is simple, fast, and always a
good starting point. Change the view group to a vertical, LinearLayout as follows:

1. In the Component Tree pane, find the top or root view directly below the Device
Screen.
2. Click the Text tab to switch to the code view of the layout.
3. In the second line of the code, change the root view group to LinearLayout. The
second line of code now looks something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

4. Make sure the closing tag at the end of the code has changed to </LinearLayout>. If it
hasn't changed automatically, change it manually.
5. The android:layout_height is defined as part of the template. The default layout
orientation a horizontal row. To change the layout to be vertical, add the following
code inside LinearLayout, below android:layout_height.
android:orientation="vertical"
6. From the menu bar, select: Code > Reformat Code…

It may say "No lines changed: code is already properly formatted".

7. Run the code to make sure it still works.


8. Switch back to Design.
9. Verify in the Component Tree pane that the top element is now a LinearLayout with
its orientation attribute set to "vertical".

2.2. Add views to the Linear Layout in the Layout Editor


In this task you will delete the current TextView (for practice), and add a new TextView and
two buttons to the LinearLayout as shown in the UI sketch for this task. Refer to the UI
diagram above, if necessary.

Add UI Elements

1. Click the Design tab to show the virtual device layout.


2. Click the TextView whose text value is "Hello World" in the virtual device layout or
the Component Tree pane.
3. Press the Delete key to remove that TextView.
4. From the Palette pane, drag and drop a Button element, a TextView, and another
Button element, in that order, one below the other into the virtual device layout.

2
BGIT 4317 | Mobile Programming Course

Adjust the UI Elements

1. To identify each view uniquely within an activity, each view needs a unique ID. And to
be of any use, the buttons need labels and the text view needs to show some text.
Double-click each element in the Component Tree to see its properties and change
the text and ID strings as follows:

Element Text ID

Top button Toast button_toast

Text view 0 show_count

Bottom button Count button_count

1. Run your app.

Solution Layout:

There should be three Views on your screen. They won't match the image
below, but as long as you have three Views in a vertical layout, you are
doing fine!

Task 3: Edit the "Hello Toast" layout in XML


In this practical, you will edit the XML code for the Hello Toast app UI layout. You will also
edit the properties of the views you have created.

1. Open res/layout/activity_main.xml in Text mode.


2. In the menu bar select Code > Reformat Code
3. Examine the code created by the Layout Editor.

3.1 Examine LinearLayout properties


A LinearLayout is required to have these properties:

 layout_width
 layout_height
 orientation

3
BGIT 4317 | Mobile Programming Course

The layout_width and layout_height can take one of three values:

 The match_parent attribute expands the view to fill its parent by width or height.
When the LinearLayout is the root view, it expands to the size of the parent view.
 The wrap_content attribute shrinks the view dimensions just big enough to enclose
its content. (If there is no content, the view becomes invisible.)
 Use a fixed number of dp (device independent pixels) to specify a fixed size, adjusted
for the screen size of the device. For example, "16dp" means 16 device independent
pixels.

The orientation can be:

 horizontal: views are arranged from left to right.


 vertical: views are arranged from top to bottom.

Change the LinearLayout of "Hello Toast" as follows:

Property Value

layout_width match_parent (to fill the screen)

layout_height match_parent (to fill the screen)

orientation vertical

3.2 Create string resources


Having the strings in a separate file makes it easier to manage them, especially if you use
these strings more than once. Also, string resources are mandatory for translating and
localizing your app as you will create one string resource file for each language.

Do the following:

1. Place the cursor on the word "Toast".


2. Press Alt-Enter (Option-Enter on the Mac).
3. Select Extract string resources.
4. Set the Resource name to button_label_toast and click OK. (If you make a mistake, undo
the change with Ctrl-Z.)
This creates a string resource in the values/res/string.xml file, and the string in your
code is replaced with a reference to the resource,
@string/button_label_toast

4
BGIT 4317 | Mobile Programming Course

5. Extract and name the remaining strings from the views as follows:

View Resource Value / String Resource name

Button Hello Toast! button_label_toast

TextView 0 count_initial_value

Button Count button_label_count

6. In the Project view, navigate to values/strings.xml to find your strings. Now, you can
edit all your strings in one place.

3.3 Resize
Similar to strings, it is a best practice to extract view dimensions from the main layout XML
file into a dimensions resource located in a file.

Do the following:

1. Look at the dimens.xml resource file. There should be values for the default screen
margins defined. For the dimensions of views, it is better not to use hard-coded
values, because that prevents views from adjusting to the screen size.
2. If necessary, change the layout_width of all elements inside the LinearLayout to
"match_parent".
3. If necessary, change the layout_height of all elements inside the LinearLayout to
"wrap_content".

3.4 Set colors and backgrounds


Styles and colors are additional properties that can be
extracted into resources. All views can have backgrounds
that can be colors or images.

Experiment with the following changes:

1. Change the text size of the show_count TextView.


"sp" stands for scale-independent pixel, and like dp,
is a unit that scales with the screen density and
user's font size preference. It is recommend you use
this unit when specifying font sizes, so they will be
adjusted for both the screen density and the user's
preference.
2. android:textSize="160sp"

5
BGIT 4317 | Mobile Programming Course

3. Extract the text size of the TextView as a dimension resource named count_text_size, as
follows:
a. Click the Text tab to show the XML code, if you haven't already done so.
b. Place the cursor on " 160sp".
c. Press Alt-Enter (Option-Enter on the Mac).
d. Click Extract dimension resource.
e. Set the Resource name to count_text_size, and click OK. (If you make a mistake,
you can undo the change with Ctrl-Z).
f. In the Project view, navigate to values/dimens.xml to find your dimensions.
The dimens.xml file applies to all devices. The dimens.xml file for w820dp
applies only to devices that are wider than 820dp.
4. Change the textStyle of the show_count TextView to bold.
5. android:textStyle="bold"
6. Change the text color in the show_count text view to the primary color of the theme.
Look at the colors.xml resource file to see how they are defined.
android:textColor="@color/colorPrimary"

7. Change the color of both the buttons to the primary color of the theme.
8. android:background="@color/colorPrimary"
9. Change the color of the text in both buttons to white. White is one of the colors
provided as an Android Platform Resource.
10. android:textColor="@android:color/white"
11. Add a background color to the TextView.
12. android:background="#FFFF00"
13. In the Layout Editor (Text tab), place your mouse cursor over this color and press Alt-
Enter (Option-Enter on the Mac).
14. Select Choose color, which brings up the color picker, pick a color you like, or go with
the current yellow, then click Choose.
15. Open values/colors.xml. Notice that colorPrimary that you used earlier is defined
here.
16. Using the colors in values/colors.xml as an example, add a resource
named myBackgroundColor for your background color, and then use it to set the
background of the text view.
<color name="myBackgroundColor">#FFF043</color>

3.5 Gravity and weight


The android:gravity attribute specifies the alignment of the content of a View within the View
itself. The counter is centered in its view with: android:gravity="center"

Do the following:

6
BGIT 4317 | Mobile Programming Course

1. Center the text in a the show_count TextView horizontally and


vertically: android:gravity="center"
2. Make the show_count TextView adjust to the size of the screen:
3. android:layout_weight="2"

Task 4: Add onClick handlers for the buttons


In this task, you will add methods to your MainActivity that execute when the user clicks on
each button.

Why: Interactive apps must respond to user input.

To connect a user action in a view to application code, you need to do two things:

 Write a method that performs a specific action when a user user clicks an on-screen
button.
 Associate this method to the view, so this method is called when the user interacts
with the view.

4.1 Add an onClick property to a button


A click handler is a method that is invoked when the user clicks on a user interface element.
In Android, you can specify the name of the click handler method for each view in the XML
layout file with the android:onClick property.

1. Open res/layout/activity_main.xml.
2. Add the following property to the button_toast button.
3. android:onClick="showToast"
4. Add the following attribute to the button_count button.
5. android:onClick="countUp"
6. Inside of activity_main.xml, place your mouse cursor over each of these method
names.
7. Press Alt-Enter (Option-Enter on the Mac), and select Create onClick event handler.
8. Choose the MainActivity and click OK.

This creates placeholder method stubs for the onClick methods in MainActivity.java.

4.2 Show a toast when the Toast button is clicked


1. Create an instance of the Toast class with the context, message, and duration.
o The context is the application context we got earlier.
o The message is the string you want to display
o The duration is one of the predefined
constants Toast.LENGTH_LONG orToast.LENGTH_SHORT.

7
BGIT 4317 | Mobile Programming Course

o Toast toast = Toast.makeText(context, "Hello Toast", Toast.LENGTH_LONG);

2. Extract the "Hello Toast" string into a string resource and call it toast_message.

o R. identifies the parameter as a resource.


o string references the name of the XML file where the resources is defined.
o toast_message is the name of the resource.
o Toast toast = Toast.makeText(context, R.string.toast_message, duration);
3. Display the toast.
4. toast.show();
5. Run your app and verify the toast shows when the Toast button is tapped.

4.3 Increase the count in the text view when the Count button
is clicked
Implement this as follows:

1. In MainActivity.java, add a private member variable mCount to track the count and
start it at 0.
2. In MainActivity.java, add a private member variable mShowCount to get the reference
of the show_count TextView.
3. In the countUp() method, increase the value of the count variable each time the button
is clicked.
4. Get a reference to the text view using the ID you set in the layout file.

In order to get this resource only once, use a member variable and set it in onCreate().
mShowCount = findViewById(R.id.show_count);

5. Set the text in the text view to the value of the count variable.
6. if (mShowCount != null)
7. mShowCount.setText(Integer.toString(mCount));
8. Run your app to verify that the count increases when the Count button is pressed.

You might also like