Professional Documents
Culture Documents
Amir Hammami
Part 1: Basics
1
Learn Android in the University
2
Learn Android in the University
Email: amir.hammami@su.edu.sa
3
Learn Android in the University
4
Learn Android in the University
- General overview: This paragraph introduces Android to students by providing a general overview of the Android
Platform.
- Setting up the development environment: In the second paragraph we move to the practical part and install
software used in the development.
Android was written based on Java language. To program Android applications, you need to know about Java and have
basic knowledge about it. Android includes a software development kit (SDK) for writing code and creating applications
for Android users.
Applications are developed for a variety of reasons: addressing business requirements, building new services, creating new
businesses, and providing games and other types of content for users. Developers choose to develop for Android in order
to reach the majority of mobile device users.
We can create an application to order foods from restaurant and monitor the status of the order: Cooking, ready, on the
way or delivered. The client can track the driver who pick the order. This app improves order tracking so you can see
where your pizza is.
Browse: Uber Eats has hundreds of restaurants to choose from. When you open the app, you can scroll through
the feed for inspiration or search for a particular restaurant or cuisine. When you find something you like, tap to
add it to your cart.
Order: When you’re ready to check out, you’ll see your address, an estimated delivery time, and the price of the
order including tax and delivery fee. When everything looks right, just tap Place order–and that’s it. We’ll
automatically use the card on file so you never need cash.
Track: Follow your order in the app. First you’ll see the restaurant accept and start prepping. Then, when the
order’s almost ready, a nearby Uber partner–in a car, on a bike, or scooter–will go to the restaurant to pick it up.
Next, they’ll drive or ride to you. You’ll be able to see their name and photo and track progress on the map.
Follow your order in the app. First you’ll see the restaurant accept and start prepping. Then, when the order’s almost
ready, a nearby Uber partner–in a car, on a bike, or scooter–will go to the restaurant to pick it up. Next, they’ll drive or
ride to you. You’ll be able to see their name and photo and track progress on the map.
5
Learn Android in the University
The SDK includes a comprehensive set of development tools including a debugger, software libraries of prewritten code, a
device emulator, documentation, sample code, and tutorials.
To develop apps using the SDK, we use the Java programming language and Extensible Markup Language (XML) files for
describing data resources. By writing the code in Java and creating a single app binary (APK file), you will have an app
that can run on both phone and tablet.
Google offers a full Java Integrated Development Environment (IDE) called Android Studio, with advanced features for
developing, debugging, and packaging Android applications. The role of the IDE is to facilitate writing code and running
applications with debug feature.
Google provides major incremental upgrades to the Android operating system every six to nine months. The latest major
release is Android 9.0 "Pie" (https://www.android.com/versions/pie-9-0/).
6
Learn Android in the University
Android Things
Raspberry Pi 3 Model B is the latest iteration of the world's most popular single board computer. It provides a quad-core
64-bit ARM Cortex-A53 CPU running at 1.2GHz, four USB 2.0 ports, wired and wireless networking, HDMI and
composite video output, and a 40-pin GPIO connector for physical interfacing projects.
7
Learn Android in the University
Linux is widely available for the Raspberry Pi. From the Raspbian Stretch distribution released by the Raspberry Pi
Foundation, to Arch Linux, versions of Ubuntu.
Since Android is based on Linux, there are several Android projects for Raspberry Pi:
emteria.OS: Perhaps the most well-known implementation of Android on Raspberry Pi, emteria.OS is available
free or as a premium product (around $21). The free option stops working every eight hours and displays a
watermark.
LineageOS 15.1 (based on Android 8.1): If you don’t like the restrictions of emteria.OS, this version of Android is
a strong alternative.
Android Things: This version is a useful internet of Things platform that runs on the Raspberry Pi 3 and later.
While it’s ideal for IoT projects, it’s less suited for running games and apps.
https://developer.android.com/things/hardware/raspberrypi
In the sequel we will discover the Android Architecture in order to understand how applications run.
8
Learn Android in the University
Platform Architecture1
Android is an open source, Linux-based software stack. The following diagram shows the major components of the
Android platform.
1 https://developer.android.com/guide/platform/
9
Learn Android in the University
A rich and extensible View System you can use to build an app’s UI, including lists, grids, text boxes, buttons, and
even an embeddable web browser
A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
A Notification Manager that enables all apps to display custom alerts in the status bar
An Activity Manager that manages the lifecycle of apps and provides a common navigation back stack
Content Providers that enable apps to access data from other apps, such as the Contacts app, or to share their own
data
Developers have full access to the same framework APIs that Android system apps use.
10
Learn Android in the University
In 2015, Google launched the Android Studio, a programming tool for Android apps, and officially no longer supported
Plugin for Eclipse.
Logically, the tools that are created for a specific task is always better. It means that you should select Android Studio to
program Android.
Now we move to the practical part of the lesson. We will install software needed to program Android applications.
Software requirements:
11
Learn Android in the University
Verify your Operation System platform. In our case we have windows 7 64 bit System, so we choose the appropriate JDK
from the list.
Install the development kit. Once the installation of the JDK is completed — it should only take a few minutes — you can
confirm it's correct by checking the Java version from the command line.
12
Learn Android in the University
Open a terminal window and enter Type java -version to verify that installation has been successful.
Set the JAVA_HOME environment variable to the installation directory of the JDK.
Click on:
Start > Control Panel > System > Advanced System Settings > Environment Variables System Variables > New
In Variable Name write ‘JAVA_HOME’ and in value copy the path of your JDK Installation directory usually inside
C:\Program Files\Java\jdkxxx
13
Learn Android in the University
Open the link and download the appropriate program file. Then run Setup
14
Learn Android in the University
At the first run, Android Studio asks you whether import settings of Android Studio verson that you may have installed in
advance or not. You can select NO.
15
Learn Android in the University
The Setup Wizard will download and install some additional SDK components. Be patient, this might take some time
depending on your Internet speed.
When the download completes, Android Studio will start, and you are ready to create your first application.
When you run Android Studio for the first time, Android Studio requires you to install Intel @ HAXM, if you do not install
it, you can download and install it.
o Operating System
o Development Platform
o Both
o JavaScript
o Java
o Python
o Swift
18
Learn Android in the University
The above diagram is a high-level picture of the development process, with the following steps:
1. Defining the idea and its requirements: Most applications start with an idea of what it should do. During this stage
the application's requirements are defined.
2. Prototyping the user interface: Use drawings and prototypes to show what the user interface would look like, and
how it would work.
3. Developing and testing the app: An app consists of one or more activities. For each activity you can use Android
Studio to do the following, in no particular order:
- Create the layout: Place UI elements on the screen in a layout, and assign string resources and menu items,
using the Extensible Markup Language (XML).
- Write the Java code: Create source code for components and tests, and use testing and debugging tools.
- Define the build: Use the default build configuration or create custom builds for different versions of your app.
4. Publishing the app: Assemble the final APK (package file) and distribute it through channels such as the Google
Play.
19
Learn Android in the University
Launch Android Studio if it is not already opened. Click "Start a new Android Studio project".
In the New Project window, give your application an Application Name, such as "Welcome".
Verify the Project location, or choose a different directory for storing your project.
20
Learn Android in the University
Every application needs at least one activity. An activity represents a single screen with a user interface and
Android Studio provides templates to help you get started. For the Welcome project, choose the simplest template (the
"Empty Activity" project template is the simplest template) available. More details about Activities will be given later.
I recommend students to create a folder called "Term1" in which they save the projects files on the hard drive.
And you should ensure that API 24: Android 7.0 Nougat is set as the Minimum SDK. (Fix this if necessary.)
At the writing of this book, choosing this API level makes your "Welcome" app compatible with 37.1% of Android devices
active on the Google Play Store.
21
Learn Android in the University
If you choose the latest API version, you will get more libraries and functionalities but less Android devices wotking with
this version. And if you choose the first versions you will get less functions but more devices.
The Android Studio window should look similar to the following figure:
22
Learn Android in the University
There are three top-level folders below your application folder: manifests, java, and res.
23
Learn Android in the University
This folder contains AndroidManifest.xml. It contains information about the Android app like the name and the icon. This
file describes all of the components of your Android application and is read by the Android run-time system when your
program is executed.
In android every application must have this file. It gives the necessary system about the application to android system.
AndroidManifest.xml contains:
You can see the basic structure of AndroidManifest.xml by opening the file (double click to open)
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
24
Learn Android in the University
You notice in this file only one activity which is MainActivity. Android applications starts by executing this activity.
All your Java language files are organized in this folder. The java folder contains three subfolders:
- com.example.gateway.welcome (or the domain name you have specified): All the files for a package are in a folder
named after the package. For the Welcome application, there is one package and it only contains
MainActivity.java
- com.example. gateway.welcome (androidTest): This folder is for your instrumented tests, and starts out with a
skeleton test file.
- com.example. gateway.welcome (test): This folder is for your unit tests and starts out with an automatically
created skeleton unit test file.
This folder contains all the resources for your application, including images, layout files, strings, icons, and styling. It
includes these subfolders:
- layout. Every activity has at least one layout file that describes the UI in XML. For Welcome, this folder contains
activity_main.xml
- mipmap. Store your launcher icons in this folder. There is a sub-folder for each supported screen density. Android
uses the screen density, that is, the number of pixels per inch to determine the required image resolution. Android
groups all actual screen densities into generalized densities, such as medium (mdpi), high (hdpi), or extra-extra-
extra-high (xxxhdpi). The ic_launcher.png folder contains the default launcher icons for all the densities
supported by your app.
- values. Instead of hardcoding values like strings, dimensions, and colors in your XML and Java files, it is best
practice to define them in their respective values file. This makes it easier to change and be consistent across your
application.
- colors.xml. Shows the default colors for your chosen theme, and you can add your own colors or change them
based on your application's requirements.
- dimens.xml. Store the sizes of views and objects for different resolutions.
- strings.xml. Create resources for all your strings. This makes it easy to translate them to other languages.
- styles.xml. All the styles for your app and theme go here. Styles help give your app a consistent look for all UI
elements.
25
Learn Android in the University
What is Gradle?
The basic one liner answer is: Gradle is an Open Source Build System to build your Android app.
Gradle takes best features of other build system and combines it to one. And because it is an JVM (Java Virtual Machine)
based build system we are free to write our own script here.
We will see later how to add libraries inside Gradle in order to add functions to your app.
Click the module folder to expand it and show the MainActivity file for the activity written in Java (the MainActivity class).
Double-click MainActivity to see the source file in the editing pane, as shown in the figure below.
At the very top of the MainActivity.java file is a package statement that defines the app package. This is followed by an
import block condensed in the above figure, with "...". Click the dots to expand the block to view it. The import statements
import libraries needed for the application, such as the following, which imports the AppCompatActivity library:
import android.support.v7.app.AppCompatActivity;
Each activity in an application is implemented as a Java class. The following class declaration extends the
AppCompatActivity class to implement features in a way that is backward-compatible with previous versions of Android:
...
are generated automatically and stored inside R.java file. And that is what we are doing here. We are selecting the
id of our layout from R.java file (R.layout.activity_main).
Android Studio shows the Design view of the layout, as shown in the figure below. This view provides a Palette pane of
user interface elements, and a grid showing the screen layout.
The fiel activity_main.xml describes the layout. It contains a visual representation of your app.
27
Learn Android in the University
Run on an emulator
Make sure that all the dependencies are installed and verify that the emulator is installed by going to:
Tools > SDK Manager > SDK Tools and make sure that Intel x86 Emulator Accelerator is installed.
28
Learn Android in the University
In order to make the emulator faster you need to increase memory configuration:
29
Learn Android in the University
30
Learn Android in the University
Connect your device to your development machine with a USB cable. If you're developing on Windows, you might need to
install the appropriate USB driver for your device.
31
Learn Android in the University
Finally run the application on your device by clicking the run button in the toolbar and select your device in the Select
Deployment Target windows. Android Studio installs the app on your connected device and starts it. You should now see
"Welcome" displayed in the application running on your device.
2.6. Exercises
Definitions
Define these terms:
- Android
- Android SDK:
- IDE
- AVD
- Android Studio
- JDK
32
Learn Android in the University
Question 2
From these pictures, complete the table below:
33
Learn Android in the University
Term Value
Android Project Name
Project Path
Android Version
Activity Name
Layout Name
Question 3
Layout files are written in:
o Java
o XML
Question 4
Android apps can only be made with Android Studio.
o True
o False
34
Learn Android in the University
We will see how the views are positioned on the screen. The layout is defined in the XML file. We use drag and drop views
on the layout.
https://developer.android.com/training/constraint-layout
35
Learn Android in the University
Use the Layout Editor to create the layout of the user interface elements, and to preview your application using different
devices and app themes, resolutions, and orientations.
In the app > res > layout folder, open the activiy_main.xml file (1).
The Android Studio Screen should look similar to the screenshot below. If you see the XML code for the UI layout, click
the Design tab below the Component Tree (8).
Using the annotated screenshot below as a guideline, explore the Layout Editor.
36
Learn Android in the University
Find the different ways in which the "Hello World" string's UI element, a TextView, is represented.
o In the Palette of UI elements (2) developers can create a text view by dragging it into the design pane.
o In the Component Tree (7), as a component in a hierarchy of UI elements called the View Hierarchy. That
is, views are organized into a tree hierarchy of parents and children, where children inherit properties of
their parents.
o In the Properties pane (4), as a list of its properties, where "Hello World" is the value of the text property
of the TextView (5).
Use the selectors above the virtual device (3) to do the following:
Use the tooltips on the icons to help you discover their function.
Switch between the Design and Text tabs (8). Some UI changes can only be made in code, and some are quicker
to accomplish in the virtual device.
37
Learn Android in the University
Note:
When you create the application and open the layout, you will not see the TextView and other components. In order to
resolve this problem you should replace:
by:
in file 'base/src/main/res/values/styles.xml'
38
Learn Android in the University
3.3. TextView
We will focus initially on TextView. TextView is what we use to display text in our app. A view is used to describe anything
on the screen. We can change the content of the TextView with "text" attribute.
We can choose a type of text, the apparence of the text like size, color and background color from a range of different
colors.
If we change the width to match_constraint, we stretch out the text to the hole width of the screen. And then we can align
to the right, left or center.
We can also change the height to stretch out the text to the hole height of the screen.
The top is linked to the top of the parent which is the constraint layout in our case.
39
Learn Android in the University
40
Learn Android in the University
41
Learn Android in the University
3.4. Button
We can drop and drop a button on the screen:
42
Learn Android in the University
43
Learn Android in the University
The button is displayed on top right of the screen without any constraint.
If we add constraints:
44
Learn Android in the University
45
Learn Android in the University
46
Learn Android in the University
Because the distance between the bottom of the button and the top of the text is 204 pixel. That's why the button is outside
the screen.
47
Learn Android in the University
We add a text field and make constraint to the top and to the left side:
49
Learn Android in the University
50
Learn Android in the University
51
Learn Android in the University
52
Learn Android in the University
3.5. Exercice
Question 1
The method called when a button is pressed is called:
o onClick
o doMethod
o action
53
Learn Android in the University
The user interface displayed on the screen of a mobile Android device consists of a hierarchy of "views". Views are
Android's basic user interface building blocks. You specify the views in XML layout files. For example, views can be
components that:
4.1. Content
In this lesson, you will create an application, add user interface element: a button and implement a click handler method
for the button.
54
Learn Android in the University
Attribute Value
55
Learn Android in the University
56
Learn Android in the University
Button - A button with a label that is usually associated with a click handler.
LinearLayout - A view that acts as a container to arrange other view. This type of view extends the ViewGroup
class and is also called a view group. LinearLayout is a basic view group that arranges its collection of views in a
horizontal or vertical row.
57
Learn Android in the University
Here is a sketch of the UI you will build in this lesson. 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.
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 (7 in the previous screenshot), find the top or root view directly below the Device
Screen.
2. Click the Text tab (8) 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"
Solution Code: Your code will look something like the following.
<TextView
android:layout_width="wrap_content"
android:layout_height="15dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
59
Learn Android in the University
Add UI Element
Click the Design tab (8) to show the virtual device layout.
Click the TextView whose text value is "Hello World" in the virtual device layout or the Component Tree pane (7).
Press the Delete key to remove that TextView.
From the Palette pane (2), drag and drop a Button element into the virtual device layout.
To identify each view uniquely within an activity, each view needs a unique ID. And to be of any use, the button need label.
Double-click the button element in the Component Tree to see its properties and change the text and ID strings as follows:
Element Text ID
Solution Layout:
60
Learn Android in the University
layout_width
layout_height
orientation
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.
Property Value
orientation vertical
Set colors
Styles and colors are additional properties that can be extracted into resources. All views can have backgrounds that can
be colors or images.
Change the text size of the button. "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.
android:textSize="40sp"
61
Learn Android in the University
android:textStyle="bold"
Change the color of the buttons to the primary color of the theme. Look at the colors.xml resource file to see how they are
defined.
android:background="@color/colorPrimary"
Change the color of the text in the button to white. White is one of the colors provided as an Android Platform Resource.
android:textColor="@android:color/white"
<Button
android:id="@+id/button_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toast"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:background="#0000FF"
/>
</LinearLayout>
62
Learn Android in the University
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.
1. Open res/layout/activity_main.xml.
2. Add the following property to the button_toast button.
android:onClick="showToast"
3. Inside of activity_main.xml, place your mouse cursor over the method name.
4. Press Alt-Enter (Option-Enter on the Mac), and select Create onClick event handler.
5. Choose the MainActivity and click OK.
This creates placeholder method stubs for the onClick method in MainActivity.java.
63
Learn Android in the University
Solution MainActivity.java:
package com.example.android.welcometoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
package com.example.android.welcometoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
The length of a toast string can be either short or long, and you specify which one by using a Toast constant.
Toast.LENGTH_LONG
Toast.LENGTH_SHORT
The actual lengths are about 3.5s for the long toast and 2s for the short toast. The values are specified in the Android
source code.
65
Learn Android in the University
In the end, we studied in this lesson user interface by implementing an application that contains one button. When the
user click on the button, a message will appear for fiew seconds.
4.8. Exercises
Question 1: Choose the correct answer:
a)
android:orientation="vertical"
android:orientation="horizontal"
66
Learn Android in the University
b)
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_width=" wrap_content"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_width=" match_parent"
android:layout_height="match_parent"
Question 2:
67
Learn Android in the University
b) Add OnClick event in order to print a log. The code inside the function is:
import android.util.Log;
68
Learn Android in the University
o Toast
o Sandwitch
o Croissant
69
Learn Android in the University
70
Learn Android in the University
Here we will make a style for the button. So add the following XML file in the drawable folder.
White_rounded_button.xml
<corners
android:radius="50dp"/>
</shape>
</item>
</selector>
5.5. Task3: Add OnClick event to display the text typed by the user
We write a function to handle the OnClick event and display the text in the EditText.
package com.ksa.ah.foodtasker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
72
Learn Android in the University
Log.i("Values", Username);
}
}
5.6. Exercice
Complete the following layout xml file to display a login screen with username and password. When we click on the
button, both information username and password will be printed in the log.
73
Learn Android in the University
74
Learn Android in the University
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="56dp"
app:theme="@style/Widget.Design.TextInputLayout">
<EditText
android:id="@+id/EditTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
75
Learn Android in the University
android:hint="Username"
android:inputType="textPersonName"
android:textSize="24dp" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="56dp"
app:theme="@style/Widget.Design.TextInputLayout">
<EditText
android:id="@+id/EditTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:textSize="24dp" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/BtnLogin"
android:layout_width="match_parent"
android:layout_height="73dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:background="@drawable/white_rounded_button"
android:onClick="LoginFunction"
android:text="Login"
android:textAllCaps="false"
android:textSize="26dp" />
</LinearLayout>
76
Learn Android in the University
Attribute Value
77
Learn Android in the University
Here is a sketch of the UI you will build in this lesson. 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.
Code: Depending on your version of Android Studio, your code will look something like the following.
<TextView
android:id="@+id/txt_counter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
78
Learn Android in the University
android:text="0"
android:textSize="200sp"
android:gravity="center"
android:textColor="#0000ff"
android:background="#faf030"
android:layout_weight="2"
/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Count"
android:textSize="30sp"
android:textColor="#ffffff"
android:background="#0000ff" />
</LinearLayout>
The android:layout_gravity attribute specifies how a view is aligned within its parent View. Because the views
match their parent in width, it is not necessary to set this explicitly. You can center a view that is narrow
horizontally in its parent: android:layout_gravity="center_horizontal"
The android:layout_weight attribute indicates how much of the extra space in the LinearLayout will be allocated
to the views that have this parameter set. If only one view has this attribute, it gets all the extra screen estate. For
multiple views, the space is pro-rated. For example, if there are two buttons and one text view, the buttons have a
weight of 1 and the text view 2, totalling 4, the buttons get ¼ of the space each, and the textview half.
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"
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.
6. Open res/layout/activity_main.xml.
7. Add the following property to the button.
android:onClick="PrintMsg"
8. Inside of activity_main.xml, place your mouse cursor over the method name.
79
Learn Android in the University
9. Press Alt-Enter (Option-Enter on the Mac), and select Create onClick event handler.
10. Choose the MainActivity and click OK.
This creates placeholder method stubs for the onClick method in MainActivity.java.
package com.example.android.welcometoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
The next step concerns how to modify the text in the TextView component.
Associate a variable in the java class MainActivity to the TextView component in the layout
Send the updated text to the TextView to display it on the user interface.
In MainActivity.java, add a private member variable TxtCounterViewto get the reference of the txt_counter TextView.
80
Learn Android in the University
Get a reference to the text view using the ID you set in the layout file.
Views, like strings and dimensions, are resources that can have an id. The findViewById() call takes the ID of a view as its
parameter and returns the view. Because the method returns a View, you have to cast the result to the view type you
expect, in this case (TextView).
In order to get this resource only once, use a member variable and set it in onCreate().
Set the text in the text view to the value of your message.
if (TxtCounterView != null)
TxtCounterView.setText("Welcome");
Run your application to verify that the text view changes when the Count button is pressed.
Solution:
package com.example.android.welcometoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (TxtCounterView != null)
TxtCounterView.setText("Welcome");
}
}
Increase the count in the text view when the Count button is clicked
Same thing to modify the counter, we need a function in the MainActivity class.
81
Learn Android in the University
In MainActivity.java, add a private member variable Count to track the count and start it at 0.
In MainActivity.java, add a private member variable TxtCounterViewto get the reference of the txt_counter TextView.
In the Increase () method, increase the value of the count variable each time the button is clicked.
Get a reference to the text view using the ID you set in the layout file.
Views, like strings and dimensions, are resources that can have an id. The findViewById() call takes the ID of a view as its
parameter and returns the view. Because the method returns a View, you have to cast the result to the view type you
expect, in this case (TextView).
In order to get this resource only once, use a member variable and set it in onCreate().
Set the text in the text view to the value of the count variable.
TxtCounterView.setText("TEXT");
82
Learn Android in the University
But this method accepts only String parameters. So we have to change the counter to text using Integer.toString():
Count = Count + 1;
if (TxtCounterView != null)
TxtCounterView.setText(TxtCount);
Or directly:
Count ++;
if (TxtCounterView != null)
TxtCounterView.setText(Integer.toString(Count));
Run your app to verify that the count increases when the Count button is pressed.
Solution:
MainActivity.java
package com.android.counterupdown;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<TextView
android:id="@+id/txt_counter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:textSize="200sp"
android:gravity="center"
android:textColor="#0000ff"
android:background="#faf030"
android:layout_weight="2"
/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""زيد
android:textSize="40sp"
android:textColor="#ffffff"
android:background="#0008ff"
android:onClick="Increase"
/>
</LinearLayout>
84
Learn Android in the University
Solution
activity_main.xml
<TextView
android:id="@+id/txt_counter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:textSize="200sp"
android:gravity="center"
android:textColor="#0000ff"
android:background="#faf030"
android:layout_weight="2"
/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""زيد
android:textSize="40sp"
android:textColor="#ffffff"
android:background="#0008ff"
android:onClick="Increase"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""ناقص
android:textSize="40sp"
android:textColor="#ffffff"
android:background="#ff08ff"
android:onClick="Decrease"
/>
</LinearLayout>
85
Learn Android in the University
MainActivity.java
package com.example.android.welcometoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
86
Learn Android in the University
87
Learn Android in the University
File: activity_main.xml
<ImageView
android:id="@+id/Books1ImageView"
android:layout_width="385dp"
android:layout_height="510dp"
android:onClick="fade"
android:scaleType="fitStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/books1" />
</android.support.constraint.ConstraintLayout>
package com.imagefading;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
88
Learn Android in the University
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
89
Learn Android in the University
<ImageView
android:id="@+id/Books1ImageView"
android:layout_width="385dp"
android:layout_height="510dp"
android:onClick="fade"
android:scaleType="fitStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/books1" />
<ImageView
android:id="@+id/Books2ImageView"
android:layout_width="385dp"
android:layout_height="510dp"
android:alpha="0"
android:onClick="fade"
android:scaleType="fitStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/books2" />
</android.support.constraint.ConstraintLayout>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
Books1ImageView.animate().alpha(0).setDuration(2000);
Books2ImageView.animate().alpha(1).setDuration(2000);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
7.4. Exercice
We want Each time w click on the screen, images will fade in fade out.
package com.myappcompany.rob.animations;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
91
Learn Android in the University
import android.view.View;
import android.widget.ImageView;
if (bartIsShowing) {
bartIsShowing = false;
Books1ImageView.animate().alpha(0).setDuration(2000);
Books2ImageView.animate().alpha(1).setDuration(2000);
} else {
bartIsShowing = true;
Books1ImageView.animate().alpha(1).setDuration(2000);
Books2ImageView.animate().alpha(0).setDuration(2000);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
92
Learn Android in the University
Switching activites, or in other words, navigating to another activity is achieved using an Intent. You simply created the
intent object and then use 'startactivity' to execute the intent.
startActivity(intent);
However, there are many ways to execute the action of creating the Intent object and starting the activity. One example is
using a Button to execute the action. You could attach an OnClickListener to this button.
package com.android.openactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
We modify the layout to add a button:
activity_main.xml
<Button
android:id="@+id/btnGoToSecondScreen"
android:text="Go To Second Screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="104dp"
/>
</RelativeLayout>
93
Learn Android in the University
94
Learn Android in the University
Activity_second_screen.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Second Screen"
android:textSize="40sp"
android:textColor="#ffffff"
android:background="#0000ff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
From the main activity we want to open the second activity by clicking on the button. We need to associate a listener to the
button.
95
Learn Android in the University
MainActivity.java
package com.android.openactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting.");
btnNavToSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked btnNavToSecond.");
}
}
Initializing a View
All these components Button and EditText are called View. We have also a predefined class named View in android. For
initializing a View from XML layout file, we have a method findViewById().
findViewById(int id)
It takes a parameter id. As I told you that every components has an specific id that is stored in R.java file. So we will
provide the id from the R file. We don’t need to go to the R file actually it is the id we have given while creating the
component. And with the name of the id a variable is created inside the R file with a unique hex value. So lets initialize our
components.
96
Learn Android in the University
setOnClickListener() method
btnNavToSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked btnNavToSecond.");
when the user click on the button, the method onClick() will be called and the code inside will be executed.
97
Learn Android in the University
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Second Screen"
android:textSize="40sp"
android:textColor="#ffffff"
android:background="#0000ff"
android:layout_weight="1"
android:gravity="center"/>
<Button
android:id="@+id/btnGoToFirstScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Go To First Screen"
android:layout_gravity="center"/>
</LinearLayout>
SecondScreen.java
package com.android.openactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_screen);
Log.d(TAG, "onCreate: Starting.");
98
Learn Android in the University
btnNavToFirst.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked btnNavToFirst.");
}
}
When we click on the button in the second activitity, it will return to the first activity or it will create another object
MainActivity.
In order to answer to this question we will create another button on each activity. The button executes the method finish()
to destroy the activity.
- From the second activity, we click on Go to the first activity button. It will open the MainActivity.
- Now we cannot confirm if the activity started is the first activity or another instance of MainActivity.
- We click on the button finish. This will close the MainActivity and return to the second activity.
- In the second activity, we click on the button finish.
- Now we have two alternatives:
a. We found the first activity: the MainActivity,
b. Or the application will be closed
- In the Emulator, the application isn't closed and we found the MainActivity.
This indicates that the button Go to the first activity creates another object and opens another
MainAcivity.
100
Learn Android in the University
File MainActivity.java
package com.android.senddata;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = EDEmail.getText().toString();
String pwd = EDPassword.getText().toString();
File activity_main.xml
101
Learn Android in the University
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Login"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Email"
android:inputType="text"
android:maxLines="1" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
<Button
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:background="@color/colorPrimary"
android:text="Sign in"
android:textColor="@android:color/white" />
</LinearLayout>
102
Learn Android in the University
File MainActivity.java
package com.android.senddata;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.EditText;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = EDEmail.getText().toString();
String pwd = EDPassword.getText().toString();
}
});
}
File: activity_main.xml
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Login"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Email"
android:inputType="text"
android:maxLines="1" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
<Button
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:background="@color/colorPrimary"
android:text="Sign in"
android:textColor="@android:color/white" />
</LinearLayout>
In order to send both email and password, we need to add these instructions:
File: SecondScreen.java
package com.android.senddata;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
104
Learn Android in the University
import android.content.Intent;
import android.widget.TextView;
TextView Email;
TextView Password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_second_screen);
Email.setText(inEmail);
Password.setText(inPwd);
}
}
File: layout_second_screen.xml
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Login Details"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="@+id/txt_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/txt_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="TextView" />
</LinearLayout>
105
Learn Android in the University
In order to obtain both email and password values in the second activity, we write:
9.4. Exercise 1
Suppose we have this activity:
106
Learn Android in the University
File: activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="@+id/button_main"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<EditText
android:id="@+id/editText_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/button_main"
android:layout_toStartOf="@+id/button_main"
android:hint="Enter Your Message Here" />
</RelativeLayout>
9.5. Exercise 2
Suppose we have this activity:
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Register"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/fullname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
107
Learn Android in the University
android:hint="Fullname"
android:inputType="text"
android:maxLines="1" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Email"
android:inputType="text"
android:maxLines="1" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
<EditText
android:id="@+id/confirmpassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Confirm Password"
android:inputType="textPassword"
android:maxLines="1" />
<Button
android:id="@+id/registerButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:background="@color/colorPrimary"
android:text="Save"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Have account ? Sign in"
android:textSize="18sp" />
</LinearLayout>
108
Learn Android in the University
Each activity contains 7 methods that will be called during the lifecycle of the activity. They describes how activity will
behave at different states. The benefit of lnowing these steps is to use them according to the purpose of the activity. For
example onCreate () is called when the activity is first created so we can start a counter. onDestroy() is called before the
activity is destroyed so we can save the value of the counter or perform user important insctructions.
Method Description
onResume called when activity will start interacting with the user.
109
Learn Android in the University
File MainActivity.java:
package com.android.activitylifecycle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
110
Learn Android in the University
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
File activity_main.xml
111
Learn Android in the University
<Button
android:text="Close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp"
android:id="@+id/btn1"/>
</RelativeLayout>
Output:
You will not see any output on the emulator or device. You need to open logcat.
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
112
Learn Android in the University
Now click on the HOME Button. You will see onPause method is invoked.
Now see on the emulator. It is on the home. Now click on the center button to launch the app again.
113
Learn Android in the University
Now see on the logcat: onRestart, onStart and onResume methods are invoked.
114
Learn Android in the University
Now click on the back button. Now you will see onPause methods is invoked.
115
Learn Android in the University
After a while, you will see onStop and onDestroy methods are invoked.
Run the application another time. Then click on the close button: you will see onPause methods is invoked. After a while,
you will see onStop and onDestroy methods are invoked.
The onCreate() and onDestroy() methods are called only once throughout the activity lifecycle.
File MainActivity.java
package com.android.activitylifecycle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
Log.d(TAG, "onCreate: ");
116
Learn Android in the University
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
btnopen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent TheIntent = new Intent(MainActivity.this, SecondScreen.class);
startActivity(TheIntent);
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
File: layout_main.xml
117
Learn Android in the University
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:text="Close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp"
android:id="@+id/btn1"/>
<Button
android:id="@+id/btn_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/btn1"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="219dp"
android:text="Open" />
</RelativeLayout>
File SecondScreen.java
package com.android.activitylifecycle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_second_screen);
Log.d(TAG, "onCreate: ");
Button btn = (Button) findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
118
Learn Android in the University
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
File: layout_second_Screen.xml
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp"
android:id="@+id/btn2"/>
</RelativeLayout>
119
Learn Android in the University
120
Learn Android in the University
121
Learn Android in the University
With this example we are able to understand the lifecycle of any activity.
122
Learn Android in the University
package com.android.chatactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
}
File: activity_main.xml
123
Learn Android in the University
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/theList"/>
</RelativeLayout>
File: list_item_layout.xml
11.3. Exercise
Given the following ListView containing list of computer components. The goal of this exercise is to add dynamically an
item to the list.
File: layout_list_products.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""المنتجات قائمة
android:textColor="#0000ff"
android:textSize="30dp"
android:gravity="right"/>
<EditText
android:id="@+id/product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint=" "المنتج إسم أكنب/>
<Button
android:id="@+id/btnadd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25dp"
android:text=" "منتج إضافة/>
<ListView
android:id="@+id/thelist"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
File: list_item_layout.xml
125
Learn Android in the University
File: ListProductsActivity.java
package com.android.listproducts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
ArrayList products;
ArrayAdapter adapter;
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_products);
products.add(";)"كمبيوتر
products.add(";)"مفاتيح لوحة
products.add(";)"فأرة
products.add(";)"شاشة
}
}
Solution
File: ListProductsActivity.java
package com.android.listproducts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_products);
126
Learn Android in the University
products.add(";)"كمبيوتر
products.add(";)"مفاتيح لوحة
products.add(";)"فأرة
products.add(";)"شاشة
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = EdProduct.getText().toString();
products.add(s);
adapter.notifyDataSetChanged();
EdProduct.setText("");
}
});
}
}
We write a component. When we click on the button. The component will be added to the list.
127
Learn Android in the University
package com.android.listview2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import android.widget.Toast;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
ListView list = (ListView) findViewById(R.id.theList);
Log.d(TAG, "onCreate: Started.");
categories.add(";)"مشويات
categories.add(";)"مأكوالت
categories.add(";)"شوارما
categories.add(";)"رز
categories.add(";)"عصيرات
categories.add(";)"ساخنة مشروبات
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
Log.d(TAG, "onItemClick: name: " + categories.get(i).toString());
Toast.makeText(MainActivity.this, "You clicked on: " +
categories.get(i).toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
File: activity_categories.xml
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/theList"/>
</RelativeLayout>
12.3. Dialog
12.4. Use DialogFragment over AlertDialog:
129
Learn Android in the University
package com.android.listview2;
// Constructor
public Product(int id, String name, double p) {
this.prod_id = id;
this.prod_name = name;
this.price = p;
}
}
File: ProductListAdapter.java
package com.android.listview2;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
130
Learn Android in the University
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Default constructor for the PersonListAdapter
* @param context
* @param resource
* @param objects
*/
public ProductListAdapter(Context context, int resource, ArrayList objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the products information
int id = ((Product)getItem(position)).getProdId();
String name = ((Product)getItem(position)).getProdName();
double price = ((Product)getItem(position)).getProdPrice();
tvId. setText(Integer.toString(prod.getProdId()));
tvName.setText(prod.getProdName());
tvPrice.setText(Double.toString(prod.getProdPrice()));
return convertView;
}
}
File: MainActivity.java
package com.android.listview2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
131
Learn Android in the University
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
}
}
File: activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/listView"/>
</RelativeLayout>
132
Learn Android in the University
File:adapter_view_layout.xml
<TextView
android:gravity="center"
android:textAlignment="center"
android:text="TextView1"
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/textView1"
android:layout_weight="80"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="20">
<TextView
android:gravity="center"
android:text="TextView2"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/textView2"/>
<TextView
android:gravity="center"
android:text="TextView3"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/textView3"
android:layout_below="@+id/textView2"/>
</LinearLayout>
</LinearLayout>
133
Learn Android in the University
134
Learn Android in the University
Images can be 'tricky' sometimes due to their varied size and quality. To avoid issues we will use an external Library
(named "Universal Image Loader") to resize render the images so we don't run into any problems.
For more information on how to use the Library check out this blog post:
http://stacktips.com/tutorials/android/universal-image-loader-library-in-android
Also don't forget to add the UniversalImageLoader dependencies to your apps Build.Gradle file.
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
package com.android.listview2;
// Constructor
public Product(int id, String name, double p, String imgPath) {
this.prod_id = id;
this.prod_name = name;
this.price = p;
this.imgUrl = imgPath;
}
135
Learn Android in the University
}
File: ProductListAdapter.java
package com.android.listview2;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.util.ArrayList;
import java.util.List;
/**
* Holds variables in a View
*/
private static class ViewHolder {
TextView id;
TextView name;
TextView price;
ImageView image;
}
/**
* Default constructor for the PersonListAdapter
* @param context
* @param resource
* @param objects
*/
public ProductListAdapter(Context context, int resource, ArrayList objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
136
Learn Android in the University
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//sets up the image loader library
setupImageLoader();
//ViewHolder object
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder= new ViewHolder();
holder.id = (TextView) convertView.findViewById(R.id.textView1);
holder.name = (TextView) convertView.findViewById(R.id.textView2);
holder.price = (TextView) convertView.findViewById(R.id.textView3);
holder.image = (ImageView) convertView.findViewById(R.id.image);
result = convertView;
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
holder.id.setText(Integer.toString(id));
holder.name.setText(name);
holder.price.setText(Double.toString(price));
return convertView;
137
Learn Android in the University
/**
* Required for setting up the Universal Image loader Library
*/
private void setupImageLoader(){
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP
}
}
File: MainActivity.java
package com.android.listview2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
138
Learn Android in the University
}
}
File: load_down_anim.xml
File: load_up_anim.xml
File: activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
139
Learn Android in the University
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/listView"/>
</RelativeLayout>
File: adapter_view_layout.xml
<ImageView
android:id="@+id/image"
android:layout_width="204dp"
android:layout_height="80dp"
android:layout_weight="10"
app:srcCompat="@drawable/ghanam" />
<TextView
android:id="@+id/textView1"
android:layout_width="139dp"
android:layout_height="80dp"
android:layout_weight="30"
android:gravity="center"
android:text="TextView1"
android:textAlignment="center" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="60">
<TextView
android:gravity="center"
android:text="TextView2"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/textView2"/>
<TextView
android:gravity="center"
android:text="TextView3"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/textView3"
android:layout_below="@+id/textView2"/>
</LinearLayout>
</LinearLayout>
140
Learn Android in the University
Run on Emulator:
141
Learn Android in the University
implementation 'com.android.support:cardview-v7:24.0.+'
File: MainActivity.java
package com.android.cardproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
142
Learn Android in the University
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCardTitle.setText("Kaaba");
}
}
File: activity_main.xml
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardCornerRadius="5dp"
app:cardElevation="15dp"
app:contentPaddingLeft="10dp"
app:contentPaddingRight="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="170dp"
android:id="@+id/cardImage"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Card Title"
android:id="@+id/cardTitle"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
143
Learn Android in the University
Add the CardView Dependency and the Universal Image Loader Dependency:
//cardview
compile 'com.android.support:cardview-v7:24.0.+'
File: activity_main.xml
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardCornerRadius="5dp"
app:cardElevation="10dp"
app:contentPaddingRight="10dp"
app:contentPaddingLeft="10dp"
app:cardMaxElevation="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="170dp"
android:id="@+id/cardImage"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/cardTitle"
android:gravity="center_vertical"
android:text="Card Title"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
File: listview_layout.xml
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"/>
</LinearLayout>
145
Learn Android in the University
File: Card.java
Package ah.com.cardview;
File: CustomListAdapter.java
package ah.com.cardview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.util.ArrayList;
import java.util.List;
146
Learn Android in the University
/**
* Holds variables in a View
*/
private static class ViewHolder {
TextView title;
ImageView image;
}
/**
* Default constructor for the PersonListAdapter
* @param context
* @param resource
* @param objects
*/
public CustomListAdapter(Context context, int resource, ArrayList<Card> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try{
//ViewHolder object
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder= new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
result = convertView;
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
147
Learn Android in the University
result = convertView;
}
holder.title.setText(title);
int defaultImage =
mContext.getResources().getIdentifier("@drawable/image_failed",null,mContext.getPackageName());
return convertView;
}catch (IllegalArgumentException e){
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage() );
return convertView;
}
/**
* Required for setting up the Universal Image loader Library
*/
private void setupImageLoader(){
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP
}
}
File: MainActivity.java
package ah.com.cardview;
import android.support.v7.app.AppCompatActivity;
148
Learn Android in the University
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
mListView = (ListView) findViewById(R.id.listView);
}
}
Don't forget to save some picture in the drawable folder.
149
Learn Android in the University
For building the Splash Screen the first thing needed is the design of the screen. Here we are going to use only a logo that
we will display in the center of the screen.
Once your project is loaded, first we will design our Splash Screen.
Here we are going to design our Splash Screen. So inside the file put the following code:
File: activity_splashscreen.xml
<ImageView
android:id="@+id/imageView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginBottom="0dp"
android:src="@drawable/act" />
</RelativeLayout>
File: SplashScreen.java
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.example.android.BTcar.R;
@Override
protected void onCreate(Bundle savedInstanceState) {
150
Learn Android in the University
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
startActivity(intent);
finish();
}
},
5000);
}
}
In the above code logo is the image file that we have already pasted inside the drawable folder, you need to put your logo
that you want in the splash screen.
When we launch the activity it will show the Splash Screen, and when the delay is finished it will display the MainActivity.
151
Learn Android in the University
For our Custom Alert Dialog create a layout. We have created the_dialog.xml. Inside this file we will design our Android
Custom Dialog.
File: the_dialog.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@color/colorPrimary">
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Success"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
152
Learn Android in the University
</LinearLayout>
</LinearLayout>
Now we need to display the above Custom Dialog Design as an Alert Dialog when a button is clicked.
For this come inside activity_main.xml and create a button inside the activity.
File: ActivityMain.xml
<Button
android:id="@+id/buttonShowDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@color/colorPrimary"
android:padding="15dp"
android:text="Android Custom Dialog Example"
android:textAllCaps="false"
android:textColor="#ffffff" />
</RelativeLayout>
Now the last task is to display our Custom Dialog when the button is clicked.
For displaying the dialog come inside MainActivity.java and write the following code.
File: MainActivity.xml
package com.android.splashscreen;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
153
Learn Android in the University
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.buttonShowDialog);
//attaching click listener
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
154
Learn Android in the University
Now run the application and you will see your custom alert dialog on clicking the button.
155
Learn Android in the University
A Fragment is a piece of an activity which enable more modular activity design. A fragment encapsulates functionality so
that it is easier to reuse within activities and layouts.
Android devices exists in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You
can also use fragments also to support different layout for landscape and portrait orientation on a smartphone.
The below image shows how two UI modules defined by fragments can be combined into one activity for a tablet design
but separated for a handset design.
156
Learn Android in the University
157
Learn Android in the University
File: MainActivity.java
package ah.com.fragements;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
File: activity_main.xml
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/containter">
</android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
158
Learn Android in the University
The adapter-layout manager pattern lets you provide different screens of content within an activity—use an adapter to fill
the content screen to show in the activity, and a layout manager that changes the content screens depending on which
button is clicked.
File: SectionsStatePagerAdapter.java
package ah.com.fragements;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.List;
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
}
Create a layout and class for each fragment. Each fragment (Fragment1, Fragment2, and Fragment3) is created with its
class definition set to extend Fragment. Also, each fragment inflates the layout associated with the screen
(fragment1_layout, fragment2_layout, and fragment3_layout), using the familiar resource-inflate design pattern.
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
final Bundle savedInstanceState) {
159
Learn Android in the University
return view;
}
}
File: Fragment1.java
package ah.com.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
final Bundle savedInstanceState) {
btnNavFrag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 1", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(0);
}
});
btnNavFrag2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 2", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(1);
}
});
btnNavFrag3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 3", Toast.LENGTH_SHORT).show();
160
Learn Android in the University
((MainActivity)getActivity()).setViewPager(2);
}
});
btnNavSecondActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 1", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return view;
}
}
File: fragment1_layout.xml
<TextView
android:id="@+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Fragment 1"
android:textColor="#ffffff"
android:textSize="40sp" />
<Button
android:id="@+id/btnNavFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment1" />
<Button
android:id="@+id/btnNavFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment2" />
<Button
android:id="@+id/btnNavFrag3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag2"
android:layout_centerHorizontal="true"
161
Learn Android in the University
android:layout_marginTop="10dp"
android:text="Go to Fragment3" />
<Button
android:id="@+id/btnNavSecondActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag3"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Second Activity" />
</RelativeLayout>
File: Fragment2.java
package ah.com.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2_layout, container, false);
btnNavFrag1 = (Button) view.findViewById(R.id.btnNavFrag1);
btnNavFrag2 = (Button) view.findViewById(R.id.btnNavFrag2);
btnNavFrag3 = (Button) view.findViewById(R.id.btnNavFrag3);
btnNavSecondActivity = (Button) view.findViewById(R.id.btnNavSecondActivity);
Log.d(TAG, "onCreateView: started.");
btnNavFrag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 1", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(0);
}
});
btnNavFrag2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 2", Toast.LENGTH_SHORT).show();
162
Learn Android in the University
((MainActivity)getActivity()).setViewPager(1);
}
});
btnNavFrag3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 3", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(2);
}
});
btnNavSecondActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 1", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return view;
}
}
File: Fragment2_layout.xml
<TextView
android:id="@+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Fragment 2"
android:textColor="#ffffff"
android:textSize="40sp"/>
<Button
android:id="@+id/btnNavFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment1" />
<Button
android:id="@+id/btnNavFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment2" />
<Button
163
Learn Android in the University
android:id="@+id/btnNavFrag3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment3" />
<Button
android:id="@+id/btnNavSecondActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag3"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Second Activity" />
</RelativeLayout>
File: Fragment3.java
package ah.com.fragements;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment3_layout, container, false);
btnNavFrag1 = (Button) view.findViewById(R.id.btnNavFrag1);
btnNavFrag2 = (Button) view.findViewById(R.id.btnNavFrag2);
btnNavFrag3 = (Button) view.findViewById(R.id.btnNavFrag3);
btnNavSecondActivity = (Button) view.findViewById(R.id.btnNavSecondActivity);
Log.d(TAG, "onCreateView: started.");
btnNavFrag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 1", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(0);
}
});
164
Learn Android in the University
btnNavFrag2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 2", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(1);
}
});
btnNavFrag3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 3", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).setViewPager(2);
}
});
btnNavSecondActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Going to Fragment 1", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return view;
}
}
File: Fragment3_layout.xml
<TextView
android:id="@+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Fragment 3"
android:textColor="#ffffff"
android:textSize="40sp" />
<Button
android:id="@+id/btnNavFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment1" />
<Button
android:id="@+id/btnNavFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag1"
165
Learn Android in the University
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment2" />
<Button
android:id="@+id/btnNavFrag3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Fragment3" />
<Button
android:id="@+id/btnNavSecondActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnNavFrag3"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Go to Second Activity" />
</RelativeLayout>
File: SecondActivity.java
package ah.com.fragements;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
}
}
File: second_activity_layout.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
166
Learn Android in the University
</RelativeLayout>
167
Learn Android in the University
package com.example.zappycode.menudemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
168
Learn Android in the University
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.settings:
Log.i("Item Selected","Settings");
return true;
case R.id.about:
Log.i("Item Selected","Help");
return true;
default:
return false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
19.4. Run
Run the App on the emulator:
169
Learn Android in the University
#2 Android Studio also have a predefined template for creating BottomNavigationView, when you create a new Activity
you can select Bottom Navigation Activity, as shown in the image.
#3 While creating an Android Project you can select Bottom Navigation Activity from the template.
170
Learn Android in the University
Now first, we will define the colors. You can change the colors to anything you want. So define the following in the
colors.xml
<resources>
<string name="app_name">Bottom Navigation Android Example</string>
<string name="title_home">Home</string>
<string name="title_dashboard">Dashboard</string>
<string name="title_notifications">Notifications</string>
<string name="title_profile">Profile</string>
</resources>
171
Learn Android in the University
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="56dp"
android:text="@string/title_home"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:itemIconTint="@color/colorNavIcon"
app:itemTextColor="@color/colorNavText"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/navigation" />
</android.support.constraint.ConstraintLayout>
Now, if you created the project using Bottom Navigation Activity template, a menu file named navigation.xml is created by
default inside the menu folder. If it is not created you can create it manually as well. Here we define all the menu items
that we need to display in the Bottom Navigation Bar.
<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/title_home" />
<item
android:id="@+id/navigation_dashboard"
android:icon="@drawable/ic_dashboard_black_24dp"
android:title="@string/title_dashboard" />
172
Learn Android in the University
<item
android:id="@+id/navigation_notifications"
android:icon="@drawable/ic_notifications_black_24dp"
android:title="@string/title_notifications" />
<item
android:id="@+id/navigation_profile"
android:icon="@drawable/ic_profile_black_24dp"
android:title="@string/title_profile" />
</menu>
So, the above codes will produce the following Layout for our Main Activity.
173
Learn Android in the University
If you have used the predefined template for creating Bottom Navigation View, then you will have some codes in the
MainActivity.java by default. We will remove those codes and change the MainActivity as shown below, so that we can
learn everything.
Creating Fragments
For each of the view we need to create a layout resource file and a fragment class to inflate the view. As we have 4 different
views to be switched we need to create 4 layout resource files and 4 java classes. Every class and resource file is almost the
same as we don’t have anything other than a simple TextView in the screens.
File: fragment_home.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Home"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>
Don’t forget to change the text value of the TextView in each file.
Creating Fragments
package net.simplifiedcoding.bottomnavigationexample;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
174
Learn Android in the University
Don’t forget to change the layout resource id (R.layout.file_name) with the layout that you want to display for the
fragment.
Switching Fragments
Now we will switch the screens or fragments when the bottom navigation menu is clicked. We also need to load some
fragment initially which is HomeFragment in this case.
First we will create a method to switch the fragment. I have created the following method named loadFragment() which is
taking Fragment is an object.
We will call the above method inside onCreate() to load the default fragment on starting.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
In onCreate() we also defined the BottomNavigationView object. We initialized it using findViewById() method and we
attached the listener to detect the Navigation Item Selection.
With the above interface we will get method, and it will be called whenever we will tap on an option from the Bottom
Navigation View. In the above method we will switch the fragments.
175
Learn Android in the University
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
fragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
So, the final code that we have for the MainActivity.java is:
package net.simplifiedcoding.bottomnavigationexample;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
176
Learn Android in the University
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
fragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
177
Learn Android in the University
Now you can design your fragments as you want, you can create some complex User Interface there.
Changing Theme
When you create a new project in Android Studio, it has the old Actionbar. And to use Toolbar first, we need to remove the
Actionbar, to do this we have to change our theme.
To change the theme go inside res->values->styles.xml. Here you will see the following
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
178
Learn Android in the University
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
File: activity_main.xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="@color/colorPrimary" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/toolbar">
<!--
-->
</LinearLayout>
</RelativeLayout>
179
Learn Android in the University
package com.android.toolbarexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
180
Learn Android in the University
Many times you see a menu on the right of the toolbar. Now let’s see how you can create this.
181
Learn Android in the University
Inside the menu directory, you need to create a new menu resource file. I have created a file named menu.xml.
182
Learn Android in the University
<item
android:id="@+id/menuSettings"
android:title="Settings" />
<item
android:id="@+id/menuLogout"
android:title="Logout" />
</menu>
Here, we have only three menu items but if you need you can add as many menu
items as you want.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
183
Learn Android in the University
Now we also need to handle the clicks on Menu Items. To do this we just need to override onOptionsItemSelected()
method.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
break;
case R.id.menuSettings:
Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
break;
case R.id.menuLogout:
Toast.makeText(this, "You clicked logout", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
After adding the above code, you will see the toast on clicking Menu Item.
Many times you see a search icon that we can use for searching something in the app. The icon is nothing but the menu. So
let’s look at how we can set up a Search option on the Toolbar.
First, you need to add a search icon to your drawable folder. You can download any magnifier icon from google images or
any other website for this. After downloading the image rename it to icon_search or any name you want, but you can only
use small letters with underscores.
Now come inside the file menu.xml that we created above. Here you need to add one more item to the starting of your
search. So modify the code as below. Remember I have added one more namespace here
<item
android:id="@+id/menuAbout"
android:title="About" />
<item
android:id="@+id/menuSettings"
android:title="Settings" />
<item
android:id="@+id/menuLogout"
android:title="Logout" />
</menu>
Now the important things in the above code is the actionViewClass=”android.support.v7.widget.SearchView”. This means
we are using the SearchView. The next thing is showAsAction=”always” and it will make the search icon visible always.
Modifying onCreateOptionsMenu()
185
Learn Android in the University
Now come inside your MainActivity.java and modify the method onCreateOptionsMenu() as shown below.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
After doing the above changes you can run your application and you will see a nice search option in your Toolbar.
186
Learn Android in the University
So first we will create a new project. And select the navigation drawer activity.
187
Learn Android in the University
Once your project is loaded your navigation drawer activity is ready. You can now run your application.
We will learn to customise the menus and to add the screens for the menus using fragment.
Now you can change the menus given in the drawer to whatever you want. To change the menu open the
activity_main_drawer.xml inside menu folder. Here is my activity_main_drawer.xml file I deleted the menus and now
we have only 3 menus (You can add as many as you want).
</group>
</menu>
We changed the text to Menu 1, Menu 2 and Menu3 and for icons we used the default android icon. You can use custom
icons just paste the icon image inside drawer folder and you can use them.
You can also customise the navigation drawer header. For this you need to go to the nav_header_main.xml file. We also
changed this file as below.
File: nav_header_main.xml
188
Learn Android in the University
android:background="@color/colorPrimaryDark"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Navigation Drawer Example"
android:textAppearance="?android:textAppearanceLarge" />
</LinearLayout>
You can see a circular red button in your activity. You can remove it if you do not need it. To remove this button go to
app_bar_main.xml inside the layout folder and remove the floating button from there.
File: app_bar_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
189
Learn Android in the University
To remove the default Hello World text view go to the content_main.xml file.
As we have removed the button we also need to modify the code inside onCreate() method of MainActivity.java so modify
it as follow or you will get error.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Now whenever we click on a navigation item from the drawer a respective screen should open, for this we will use
fragments. As we have three navigation menus we will create three layouts inside our layout folder.
Right click on layouts folder and create a new layout resource file. I named it fragment_menu_1.xml,
fragment_menu_2.xml and fragment_menu_3.xml. Write the following xml code inside all these files.
File: fragment_menu_1.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Menu 1"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
190
Learn Android in the University
All the three files contains the same code only for the text I changed it to Menu 1, Menu 2 and Menu3 for the respective
files.
You can design the screens according to your application requirement but for now I am justing putting a normal TextView
as it is an example demonstrating the concept only.
So we have the layouts now we will put these screens inside your activity using fragments. For this we need a FrameLayout
so go inside content_main.xml file and add a FrameLayout.
File: content_main.xml
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
So create 3 java classes inside your package named Menu1, Menu2 and Menu3 and write the following code.
File: menu1.java
package net.simplifiedcoding.navigationdrawerexample;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.fragment_menu_1, container, false);
}
191
Learn Android in the University
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Menu 1");
}
}
For the other two classes code will be the same, you only need to change R.layout.fragment_menu_1 with the respective
layout file for your fragment.
Now come inside MainActivity.java and empty the method onNavigationItemSelected(MenuItem item) as follows.
If you try to run app now it will give error, as we have changed the menu items and ids. So first go inside MainActivity.java
(or the java file for your navigation drawer activity). And modify the overriden method
onNavigationItemSelected(MenuItem item) as follows.
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
192
Learn Android in the University
Here we removed the previous if else conditions and added our own according to the customised menu ids.
package net.simplifiedcoding.navigationdrawerexample;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
193
Learn Android in the University
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
194
Learn Android in the University
You may have already seen Android TabLayout Example in the apps you use daily. For example WhatsApp the home
screen is an Android TabLayout Example from where we switch to calls, chats and contacts.
Android TabLayout provides horizontal layout to display tabs. We can display more screens in a single screen using tabs.
User can swipe the tabs quickly as you can see in the image below.
We have to add design support library to the dependencies. So right click on app and to go module settings.
195
Learn Android in the University
Now go to dependencies tab and click on the + button and select library dependency.
196
Learn Android in the University
We have to create the layout resource files for our tabs. As in this project we will be displaying 3 tabs so we need to create
3 layout files.
You can see in the image we have tab1.xml, tab2.xml and tab3.xml. All these files are having the same code you can see
below.
File: tab1.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
197
Learn Android in the University
Just change the android:text=”Tab tab_number”,for every layout file to see the tabs are switching or not.
For these 3 layout resource files we also need to create 3 java classes that will contain these resource as fragment.
Create these 3 classes in your project (Tab1, Tab2, Tab3). The code would be the same for every class. Write the following
code inside these 3 classes.
File: Tab1.java
package com.android.androidtablayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
You just need to change the R.layout.tab1 for Tab1.java, R.layout.tab2 for Tab2.java and so on.
198
Learn Android in the University
We need a pager adapter to swipe views. So create a new class named Pager.java. and write the following code.
File: Pager.java
package com.android.androidtablayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
//Extending FragmentStatePagerAdapter
public class Pager extends FragmentStatePagerAdapter {
Removing Actionbar
Now one thing we just forget. We have to remove the action bar and we will use the toolbar instead. So go to values ->
styles.xml and change the app theme.
199
Learn Android in the University
File: styles.xml
<resources>
<!-- Base application theme. -->
<!-- changing it to no actionbar -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
Now we will create our TabLayout, so come inside activity_main.xml and write the following code.
File: activity_main.xml
<LinearLayout
android:id="@+id/main_layout"
android:orientation="vertical"
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</LinearLayout>
200
Learn Android in the University
In the above code we have implemented the interface OnTabSelectedListener. As we implemented an interface to our class
we have to override the methods of this interface. Override the following methods inside MainActivity.java.
@Override
public void onTabSelected(TabLayout.Tab tab) {
@Override
public void onTabUnselected(TabLayout.Tab tab) {
@Override
public void onTabReselected(TabLayout.Tab tab) {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
Now at last we only need to swipe the view when a new tab is selected. For this go to the overriden method
onTabSelected() and write the following code.
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
File: MainActivity.java
package com.android.androidtablayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
202
Learn Android in the University
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
203
Learn Android in the University
References
Books
- Android 5 Programming by Example – Kyle Mew – 2015 Packt Publishing
Websites
- https://codingwithmitch.com
- https://www.simplifiedcoding.net
- https://www.tutorialspoint.com/android/
- https://www.tutlane.com/tutorial/android
204