You are on page 1of 205

Dr.

Amir Hammami

Learn Android in the University

Part 1: Basics

Learn Android in the University


Shaqra University
1441-1440
Learn Android in the University

Learn Android in the University


Part 1: Basics

Dr. Amir Hammami

Computer Science Department


Faculty of Business and Administration
Shaqra University
Afif Branch
Kingdom of Saudi Arabia

1
‫‪Learn Android in the University‬‬

‫بسم هللا الرحمن الرحيم‬


‫في إطار التدريس بقسم علوم الحاسب وبالتحديد في مقرر مواضيع مختارة في علوم الحاسب (‪ )I‬و (‪ )II‬الذي يعتني بتعليم‬
‫الطالب برمجة تطبيقات الجوال‪ ،‬تم تأليف هذا الكتاب بعنوان‪" :‬تعليم األندرويد في الجامعة" في جزئين‪.‬‬
‫يحتوي الجزء األول من الكتاب على تفاصيل املحاضرات التي تم تدريسها خالل الفصل األول طبقا للخطة الدراسية مع بعض‬
‫التعديالت واإلضافات التي تهدف إلى االرتقاء بمستوى طالب الحاسب اآللي في اململكة العربية السعودية‪.‬‬
‫يمتاز الكتاب بسهولة العبارة وذلك لتيسير دراسته من قبل طالب اململكة وخاصة طالب جامعة شقراء ويمتاز كذلك بالتدرج‬
‫ََ‬
‫في التعلم أي االنتقال من السهل اليسير إلى األكثر تعقيد حتى يتدرج الطالب وتصبح لديه َملكة للتعلم والبرمجة‪.‬‬
‫من مميزات الكتاب أيضا تفصيل املحاضرات والشروحات باالعتماد على الرسوم واألكواد الجاهزة التي تم برمجتها خالل‬
‫حصص العملي‪ .‬فما على الطالب إال التشمير عن ساعد الجد للتعلم والبرمجة واالستفادة من محتوى الكتاب‪.‬‬
‫الدكاترة واألساتذة املهتمين بهذا املقرر يجدون هنا مرجعا هاما ومادة دسمة لكتابة محاضراتهم بحيث يختزل لهم الوقت‬
‫والبحث‪.‬‬
‫إعتمدت على بعض املواقع والكتب املذكورة في آخر الكتاب‪.‬‬
‫وأخيرا نرحب بكل مالحظة ونقد بناء لتحسين هذا املنتوج العلمي والعمل الجامعي‪.‬‬
‫كما أني أتوجه بالشكر إلى معالي مدير جامعة شقراء الدكتور عوض األسمري وإلى عميد كلية إدارة األعمال الدكتور مطلق‬
‫الروقي الذي إستقبلني في كليته ويسر لي العمل بفضل هللا في قسم علوم الحاسب اآللي‪ .‬الشكر متوجه أيضا إلى وكيل فرع‬
‫الحاسب الدكتور محمد املرشدي وكذلك كامل أعضاء هيئة التدريس‪.‬‬
‫د‪ .‬أمير محمد املنصف الحمامي‬

‫‪2‬‬
Learn Android in the University

About the Author


Dr. Amir Hammami received his Engineer degree (Computer Science) from INSAT, Tunisia in 2003, Majester diploma
from Paul Sabatier University Toulouse France in 2004 and Ph. D (Computer Science) from Paul Sabatier University
Toulouse France in 2007. He has more than 10 years of experience in teaching undergraduate as well as postgraduate
students of Computer Science, Information Technology and Computer Applications on ENIG Gabes University Tunisia.
He has authored more than 10 research papers on software engineering in leading international journals and conferences.
His current research interests are Internet of Things, Software Engineering (SE) such as Mobile Development, Database
and Web programming.

Email: amir.hammami@su.edu.sa

Mobile: 00966590320806 (WhatsApp)

3
Learn Android in the University

4
Learn Android in the University

Lesson 1. Get Started


1.1. Content
This first lesson contains two mains parts:

- 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.

1.2. General Overview


Android is an operating system on mobile phones (and now it is also used on HD player, TV), developed by Google and
based on the Linux platform. Previously, Android was developed by Android Company (thereafter Google acquired in
2005).

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.

Example of such application is Uber Eats (https://www.ubereats.com/en-SA/). Main services are:

 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

Figure 1.1. Android features

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.

Here is usefull information in order to install Android Things on Raspberry Pi:

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.

Figure 1.2. Android Platform Architecture

1 https://developer.android.com/guide/platform/
9
Learn Android in the University

(1) The Linux Kernel


The foundation of the Android platform is the Linux kernel. We found the major Operating System functionalities such as
threading and low-level memory management.

(2) Hardware Abstraction Layer (HAL)


The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware capabilities to the higher-
level Java API framework. The HAL consists of multiple library modules, each of which implements an interface for a
specific type of hardware component, such as the camera or bluetooth module.

(3) Android Runtime


For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process and with its own
instance of the Android Runtime (ART). ART is written to run multiple virtual machines on low-memory devices by
executing DEX files, a bytecode format designed specially for Android that's optimized for minimal memory footprint.

(4) Native C/C++ Libraries


Many core Android system components and services, such as ART and HAL, are built from native code that require native
libraries written in C and C++.

(5) Java API Framework


The entire feature-set of the Android OS is available to the developer through APIs written in the Java language. These
APIs form the building blocks to create Android apps by simplifying the reuse of core, modular system components and
services, which include the following:

 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.

(6) System Applications


Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing, contacts, and more.

We develop our applications in this layer.

10 
Learn Android in the University

1.3. Setup Development Environment


Android Development Tools
Before 2015, you need to install Eclipse (A programming tool for Java) to program Android applications, then you need to
install plugin into Eclipse, which allows you to program Android applications on Eclipse.

Figure 1.3. Eclipse IDE

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.

Figure 1.4. Android Studio IDE

Now we move to the practical part of the lesson. We will install software needed to program Android applications.

Software requirements:

 Java Development Kit (JDK)


 Android Studio with SDK

We need JDK because Android development is based on Java programming language.

11 
Learn Android in the University

Task 1. Install Java


To download the Java Standard Edition () Development Kit (JDK): type in your preferred web navigator: "Download JDK
8"

Figure 1.5. Download Java Development Kit (JDK 8)

Verify your Operation System platform. In our case we have windows 7 64 bit System, so we choose the appropriate JDK
from the list.

Figure 1.6. Select the appropriate file to download

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

Figure 1.7. Install Java

Open a terminal window and enter Type java -version to verify that installation has been successful.

Figure 1.8. Verify the Java version

Now we need to add System Environment Variable to Windows.

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

 Variable name: JAVA_HOME


 Variable value: C:\Program Files\Java\jdk1.8.0_181

If the variable already exists, update it to this version of the JDK.

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

Figure 1.9. Configure Java

Now apply the changes and its done.

Task2. Install Android Studio


We have to download the IDE from the Android official website. Type in the web navigator: "Download Android Studio"

Figure 1.10. Download Android Studio

Open the link and download the appropriate program file. Then run Setup

14 
Learn Android in the University

Figure 1.11. Install Android Studio

After finishing installation, we start the program.

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.

Figure 1.12. Start Android Studio

15 
Learn Android in the University

Figure 1.13. Start Download Additional Components

The Setup Wizard will download and install some additional SDK components. Be patient, this might take some time
depending on your Internet speed.

Download SDK components

Figure 1.14. Download Additional Components


16 
Learn Android in the University

When the download completes, Android Studio will start, and you are ready to create your first application.

Task 3. Installing Intel® HAXM


The Intel Hardware Accelerated Execution Manager (Intel® HAXM) is a hardware-assisted virtualization engine
(hypervisor) that uses Intel Virtualization Technology (Intel® VT) to speed up Android app emulation on a host machine.

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.

Figure 1.15. Start Installing Intel HAXM

Figure 1.16. Finish installing Intel HAXM


17 
Learn Android in the University

Finally, in this lesson, we:

 Introduced Android as a linux operating system and a development platform;


 Installed Java and Android Studio IDE to write code.

1.4. Quick Quiz


1. Android is:

o Operating System
o Development Platform
o Both

2 Android Studio apps are written in:

o JavaScript
o Java
o Python
o Swift

3. Android Studio IDE means:

o Android Studio International Development Environment


o Android Studio Integrated Development Environment
o Android Studio Information Decrease Envelop

18 
Learn Android in the University

Lesson 2. Create Welcome Application


2.1. Content
We talk in this lesson about:

- How to develop an Android Application: software stages,


- Create your first application,
- Run the application.

2.2. The development process


An Android application project begins with an idea and a definition of the requirements necessary to realize that idea. As
the project progresses, it goes through design, development, and testing.

Figure 2.1. The development Process

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.

- Register the activity: Declare the activity in the manifest file.

- 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

2.3. Implement the Welcome application


In this task, you will implement the "Welcome" application to verify that Android studio is correctly installed and learn the
basics of developing with Android Studio.

Launch Android Studio if it is not already opened. Click "Start a new Android Studio project".

Figure 2.2. Launch Android Studio

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.

In our example, the project path is: "D:/Development/AndroidDevelopment/Term1/Welcome"

Then we have to select an API version which corresponds to Android version.

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.

These are the settings used by the examples in this book.

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.

After these steps, Android Studio:

- Creates a folder for your Android Studio Projects.


- Builds your project with Gradle (this may take a few moments). Android Studio uses Gradle as it's build system.
See the Configure your build developer page for more information.
- Opens the code editor with your project.
- Displays a tip of the day.

The Android Studio window should look similar to the following figure:

22 
Learn Android in the University

2.4. Explore the project structure


We will explore how the project files are organized in Android Studio.

There are three top-level folders below your application folder: manifests, java, and res.

23 
Learn Android in the University

Expand the manifests folder.

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:

- Java Package name of the application


- It describes the app icon, theme and label
- It describes all the components of your application like, activities, broadcast receivers, services etc.
- It describes all the permissions your application has to access the restrict part of android system
- It also tells the minimum api level for your application.

You can see the basic structure of AndroidManifest.xml by opening the file (double click to open)

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gateway.welcome">

<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" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</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.

Expand the java folder.

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.

Expand the res folder.

This folder contains all the resources for your application, including images, layout files, strings, icons, and styling. It
includes these subfolders:

- drawable. Store all your app's images in this folder.

- 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.

Expand the values subfolder within the res folder.

It includes these subfolders:

- 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.

Viewing and editing Java code


Components are written in Java and listed within module folders in the java folder in the Project: Android view. Each
module name begins with the domain name (such as com.example.android) and includes the application name.

The following example shows an activity component:

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:

public class MainActivity extends AppCompatActivity {

...

- onCreate(Bundle savedInstanceState): This is an overridden method. It is inside the AppCompatActivity class.


This method will be executed when the application is opened (the activity is created). So basically you can think
that it is the main method.
- Bundle: It is another predefined class. It is basically used for passing data between android activities.
- setContentView(R.layout.activity_main): This method takes a layout and it set the view as the layout to the
activity. We created a layout named activity_main.xml. As I told you before that all the ids for all the components
26 
Learn Android in the University

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).

Viewing and editing layouts


Layout resources are written in XML and listed within the layout folder in the res folder in the Project: Android view. Click
res > layout and then double-click activity_main.xml to see the layout file in the editing pane.

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

2.5. Run your application


In this task, you will run your Welcome application. You can now run the application on a real device or an emulator.

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.

We have to create a virtual device.

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

Now we can select our AVD Android Virtual Device:

You can see that the application is running on the Emulator.

30 
Learn Android in the University

Run on real device

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

Lesson 3. Basic UI design


3.1. Content
We talk about basic UI designing in android and the ContstraintLayout for the designing of the screen.

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.

This link details the contstraint layout.

https://developer.android.com/training/constraint-layout

3.2. Explore the Layout Editor


With Android Studio, we create a new project.

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 Visually, in the Design pane (6).

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:

o Change the theme for your app.

o Change the rotation to landscape.

o Use a different version of the SDK.

o Preview layout variants such as a right-to-left layout direction.

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:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> </style>

by:

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar"> </style>

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.

We can add constraints:

The top is linked to the top of the parent which is the constraint layout in our case.

39 
Learn Android in the University

We can add margins:

dp: density independent pixel

We can add padding:

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:

We run the app on the emulator.

42 
Learn Android in the University

We obtain this result.

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

Let's see whats happening?

45 
Learn Android in the University

If we rotate the screen, the button is gone.

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.

If we change the constraint to the top and the left:

And we run the application:

47 
Learn Android in the University

If we rotate the screen:

The constaints are always the same.


48 
Learn Android in the University

We add a text field and make constraint to the top and to the left side:

We run the app:

49 
Learn Android in the University

If we rotate the screen

50 
Learn Android in the University

We notice that the width of the text field is always fixed.

If we add constraint to the right side:

Let's se how it works.

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

Lesson 4. Interactive UI (User Interface)


We continue exploring Android features and increase student contact with Android by programming an interactive
application.

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:

 display text (TextView class)


 allow you to edit text (EditText class)
 represent clickable buttons (Button class) and other interactive components
 contain scrollable text (ScrollView) and scrollable items (RecyclerView)
 show images (ImageView)
 contain other views and position them (LinearLayout).
 pop up menus and other interactive components.

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.

- Create new project


- Modify the default layout to LinearLayout
- Add button view to the layout
- Add OnClick event to the button in order to show a message

4.2. Application overview


The "Welcome Toast" application will consist of one button. When you click on this button, it will display a short message,
or toast, on the screen.

Here's what the finished app will look like:

54 
Learn Android in the University

4.3. Task 1. Create a new "Welcome Toast" project


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

Attribute Value

Application Name Welcome Toast

Company Name com.example.android or your own domain

Phone and Tablet Minimum SDK API19: Android 4.4 KitKat

Template Empty Activity

Generate Layout file box Checked

Backwards Compatibility box Checked

55 
Learn Android in the University

56 
Learn Android in the University

4.4. Task 2: Add views to "Welcome Toast" in the Layout Editor


In this task, you will create and configure a user interface for the "Welcome Toast" application by arranging view UI
components on the screen.

Views used for Welcome Toast are:

 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.

Change the view group to a LinearLayout


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

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

1. In the Component Tree pane (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"

6. From the menu bar, select: Code > Reformat Code…


It may say "No lines changed: code is already properly formatted".
7. Run the code to make sure it still works.
8. Switch back to Design.
9. Verify in the Component Tree pane that the top element is now a LinearLayout with its orientation attribute set to
"vertical".

Solution Code: Your code will look something like the following.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
58 
Learn Android in the University

<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 Button to the Linear Layout in the Layout Editor


In this task you will delete the current TextView (for practice), and add one button to the LinearLayout.

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.

Adjust the UI Element

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

Top button Toast button_toast

Solution Layout:

There should be one View on your screen.

60 
Learn Android in the University

4.5. Task 3: Edit the "Welcome Toast" layout in XML


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

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


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

Examine LinearLayout properties


A LinearLayout is required to have these properties:

 layout_width
 layout_height
 orientation

The layout_width and layout_height can take one of three values:

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

The orientation can be:

 horizontal: views are arranged from left to right.


 vertical: views are arranged from top to bottom.

Change the LinearLayout of "Welcome Toast" as follows:

Property Value

layout_width match_parent (to fill the screen)

layout_height match_parent (to fill the screen)

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.

Experiment with the following changes:

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

Change the textStyle of the button to bold.

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"

Sample Solution: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">

<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

4.6. Task 4: Add onClick handlers for the button


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

Why: Interactive apps must respond to user input.

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

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

Add an onClick property to a button


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

1. Open res/layout/activity_main.xml.
2. Add the following property to the button_toast button.

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;

public class MainActivity extends AppCompatActivity {


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

public void showToast(View view) {


}
}

Show a toast when the Toast button is clicked


A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the
message and the current activity remains visible and interactive. Toasts provide another way for you to test the
interactivity of your app.

package com.example.android.welcometoast;

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

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

public void showToast(View view) {


// Create a toast and show it.
Toast toast = Toast.makeText(this, "Welcome", Toast.LENGTH_LONG);
toast.show();
}
}
64 
Learn Android in the University

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.

4.7. Task 5: Run the App on the Emulator

If we click on the button, a message will appear on the screen:

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:

a) Create an Android App containing a button in the center.

67 
Learn Android in the University

b) Add OnClick event in order to print a log. The code inside the function is:

public void ClickFunction(View view) {


Log.i("Info", "Welcome in KSA");
}

Don't forget to import the library:

import android.util.Log;

When we click on the button, we obtain a log.

68 
Learn Android in the University

Question 3: A popup message in Android is known as a:

o Toast
o Sandwitch
o Croissant

69 
Learn Android in the University

Lesson 5. Type Text and obtain information from the user


5.1. Content
User can type text and other information like username and password in a Login Screen. In this lesson we will study how
to add EditText view in order to obtain text from user.

5.2. Application Overview

5.3. Task 1: Add EditText view to the layout


In the activity_main.xml add an EditText by drag and drop the view to the layout. Change the width to stretch to all the
screen width and make margins.

70 
Learn Android in the University

5.4. Task 2: Add a Button


Then add a button under the textfield.

Here we will make a style for the button. So add the following XML file in the drawable folder.

White_rounded_button.xml

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true">
<shape>
<solid
android:color="@color/link_blue"/>
<stroke
android:color="@color/black"
android:width="1dp"/>
<corners
android:radius="50dp"/>
</shape>
</item>
<item>
<shape>
<solid
android:color="@color/white"/>
<stroke
android:color="@color/grey"
android:width="1dp"/>
71 
Learn Android in the University

<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;

public class MainActivity extends AppCompatActivity {

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

public void LoginFunction(View view) {

72 
Learn Android in the University

EditText EditTextUsername = (EditText) findViewById(R.id.EditTextUsername);

String Username = EditTextUsername.getText().toString();

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

5.7. A Better solution


A better solution consists of using LinearLayout and make views in the center of the screen.

74 
Learn Android in the University

The layout xml file is:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<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

Lesson 6. Counter up and down


6.1. Content
In this lesson, you will create an application that increases a counter.

- We start by defining the layout


- Then we add onClick event handler

6.2. Application overview


The "Increase Counter" application will consist of one button and a textview. When you click on this button, it will
increment the counter; the total count of mouse clicks will be displayed in the text view.

Here's what the finished application will look like:

6.3. Task 1. Create a new "Counter" project


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

Attribute Value

Application Name Counter

Company Name com.example.android or your own domain

Phone and Tablet Minimum SDK API19: Android 4.4 KitKat

Template Empty Activity

Generate Layout file box Checked

Backwards Compatibility box Checked

77 
Learn Android in the University

6.4. Task 2: Add views to "Counter" in the Layout Editor


In this task, you will create and configure a user interface for the "Counter" app by arranging view UI components on the
screen.

Views used for Welcome Toast are:

 TextView – A view that displays text.


 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.

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.

Explore the Layout Editor


Use the Layout Editor to create the layout of the user interface elements, and to preview your app using different devices
and app themes, resolutions, and orientations.

Code: Depending on your version of Android Studio, your code will look something like the following.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
android:paddingBottom"16dp"
android:paddingLeft"16dp"
android:paddingRight"16dp"
android:paddingTop="16dp"
tools:context=".MainActivity">

<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>

Gravity and weight


Specifying gravity and weight properties gives you additional control over arranging views and content in linear layouts.

 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"

6.5. Task 4: Add onClick handler for the button


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

Why: Interactive apps must respond to user input.

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

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

Add an onClick property to a button


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

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;

public class MainActivity extends AppCompatActivity {

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

public void PrintMsg(View view) {


}
}

The next step concerns how to modify the text in the TextView component.

To display a message in the text view:

 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.

Implement this as follows:

In MainActivity.java, add a private member variable TxtCounterViewto get the reference of the txt_counter TextView.

80 
Learn Android in the University

private TextView TxtCounterView;

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().

TxtCounterView = (TextView) findViewById(R.id.txt_counter);

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;

public class MainActivity extends AppCompatActivity {

private TextView TxtCounterView;

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

TxtCounterView = (TextView) findViewById(R.id.txt_counter);


}

public void PrintMsg(View view) {

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

To display the current count in the text view:

 Keep track of the count as it changes.


 Send the updated count to the text view to display it on the user interface.

Implement this as follows:

In MainActivity.java, add a private member variable Count to track the count and start it at 0.

private int Count = 0;

In MainActivity.java, add a private member variable TxtCounterViewto get the reference of the txt_counter TextView.

private TextView TxtCounterView;

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().

TxtCounterView = (TextView) findViewById(R.id.txt_counter);

Set the text in the text view to the value of the count variable.

In order to set a text in the text view we use method setText():

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;

int TxtCount = Integer.toString(Count) ;

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;

public class MainActivity extends AppCompatActivity {

private int Count = 0;


private TextView TxtCounterView;

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

TxtCounterView = (TextView) findViewById(R.id.txt_counter);


}

public void Increase(View view) {


Count++;
if (TxtCounterView != null)
TxtCounterView.setText(Integer.toString(Count));
}
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
83 
Learn Android in the University

<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>

6.6. Task 5: Run the App on the Emulator

84 
Learn Android in the University

6.7. Exercise: Add button to decrease the counter


In this exercise we will add another button used to decrease the counter.

Solution

The layout contains:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">

<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

Then add another method Decrease in MainActivity class:

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;

public class MainActivity extends AppCompatActivity {

private int Count = 0;


private TextView TxtCounterView;

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

TxtCounterView = (TextView) findViewById(R.id.txt_counter);


}

public void Increase(View view) {


Count++;
if (TxtCounterView != null)
TxtCounterView.setText(Integer.toString(Count));
}
public void Decrease(View view) {
Count--;
if (TxtCounterView != null)
TxtCounterView.setText(Integer.toString(Count));
}

86 
Learn Android in the University

Lesson 7. Image Animation


7.1. Content

7.2. Image Fading


Task1: Prepare Image File
Start a new Android Project called ImageFading.

Copy this image into drwable folder:

Task2: Place image in the layout

87 
Learn Android in the University

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
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="com.imagefading.MainActivity">

<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>

Task3: Apply Fading Code


When we click on the image, it will disappear. So we add OnClick event associated to the image. And we write the
following code in MainActivity.java

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

public class MainActivity extends AppCompatActivity {

public void fade(View view) {

Log.i("Info", "Imageview tapped");

ImageView Books1ImageView = (ImageView) findViewById(R.id.Books1ImageView);


Books1ImageView.animate().alpha(0).setDuration(2000);
}

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

Task4: Run on the emulator

7.3. Image Fade In Fade Out


Task1: Add Another Image
We add another image and set the alpha attribute to zero.

89 
Learn Android in the University

Task2: Place the second image in the layout


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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="com.myappcompany.rob.animations.MainActivity">

<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>

Task3: Apply Fading In to Image 1 and Fade Out to Image 2


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;

public class MainActivity extends AppCompatActivity {


90 
Learn Android in the University

public void fade(View view) {

Log.i("Info", "Imageview tapped");

ImageView Books1ImageView = (ImageView) findViewById(R.id.Books1ImageView);


ImageView Books2ImageView = (ImageView) findViewById(R.id.Books2ImageView);

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);
}
}

Task4: Run on the emulator

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;

public class MainActivity extends AppCompatActivity {

boolean bartIsShowing = true;

public void fade(View view) {

Log.i("Info", "Imageview tapped");

ImageView Books1ImageView = (ImageView) findViewById(R.id.Books1ImageView);


ImageView Books2ImageView = (ImageView) findViewById(R.id.Books2ImageView);

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

Lesson 8. Switching between activities


8.1. Content
In this lesson, we will study how to open a new activity from a first activity.

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.

Intent intent = new Intent(MainActivity.this, SecondScreen.class);

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.

8.2. Start New Project: OpenActivity


Create new project with an empty activity.

Main activity contains the following java code:

package com.android.openactivity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@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

<?xml version="1.0" encoding="utf-8"?>


<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">

<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

We create another activity called SecondScreen

94 
Learn Android in the University

Activity_second_screen.xml

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
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=".SecondScreen">

<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>

Notice that the manifest file will contains two activities:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.openactivity">

<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" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<activity android:name=".SecondScreen"></activity>
</application>

</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;

public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting.");

Button btnNavToSecond = (Button) findViewById(R.id.btnGoToSecondScreen);

btnNavToSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked btnNavToSecond.");

Intent intent = new Intent(MainActivity.this, SecondScreen.class);


startActivity(intent);
}
});

}
}

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.

Come inside onCreate() method and write the following code

Button btnNavToSecond = (Button) findViewById(R.id.btnGoToSecondScreen);

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.");

Intent intent = new Intent(MainActivity.this, SecondScreen.class);


startActivity(intent);
}
});

when the user click on the button, the method onClick() will be called and the code inside will be executed.

We run the application in Emulator:

8.3. Open the first activity


From the second activity we can open the first activity by doing the same code.

We modify the layout and add a button in the file activity_second_screen.xml

97 
Learn Android in the University

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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=".SecondScreen"
android:orientation="vertical">

<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>

Then we modify the second activity.

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;

public class SecondScreen extends AppCompatActivity {


private static final String TAG = "SecondScreen";

@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

Button btnNavToFirst = (Button) findViewById(R.id.btnGoToFirstScreen);

btnNavToFirst.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked btnNavToFirst.");

Intent intent = new Intent(SecondScreen.this, MainActivity.class);


startActivity(intent);
}
});

}
}

We run the application in Emulator:

Here a question will be rised:

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.

- We start the application,


- From the MainActivity, we click on the button Go to the second activity. It will open the second activity,
99 
Learn Android in the University

- 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

Lesson 9. Send Data from an Activity to another


9.1. Content
In this lesson we will study how to send data from one activity to another using an Intent. Using intents to pass data
between activities is the best way if you are sending small amounts of data.

We will divide this lesson into two parts:

- Get text from a Text Field


- Send this text to another activity

9.2. Display Message


Create a new project and add a Text Field view:

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;

public class MainActivity extends AppCompatActivity {


Button btn1;
EditText EDEmail;
EditText EDPassword;

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

EDEmail = (EditText) findViewById(R.id.email);


EDPassword = (EditText) findViewById(R.id.password);

btn1 = (Button) findViewById(R.id.loginButton);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = EDEmail.getText().toString();
String pwd = EDPassword.getText().toString();

Toast.makeText(getBaseContext(), "Email is: " + email + "\nPassword is: " + pwd,


Toast.LENGTH_LONG).show();
}
});
}

File activity_main.xml

101 
Learn Android in the University

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
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"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
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>

102 
Learn Android in the University

9.3. Send text using Intent


We create a second activity and modify code:

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;

public class MainActivity extends AppCompatActivity {


Button btn1;
EditText EDEmail;
EditText EDPassword;

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

EDEmail = (EditText) findViewById(R.id.email);


EDPassword = (EditText) findViewById(R.id.password);

btn1 = (Button) findViewById(R.id.loginButton);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = EDEmail.getText().toString();
String pwd = EDPassword.getText().toString();

Intent intent = new Intent(MainActivity.this, SecondScreen.class);


intent.putExtra("var_email", email);
intent.putExtra("var_pwd", pwd);
startActivity(intent);

}
});
}

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
103 
Learn Android in the University

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:

Intent intent = new Intent(MainActivity.this, SecondScreen.class);


intent.putExtra("var_email", email);
intent.putExtra("var_pwd", pwd);
startActivity(intent);

The second activity contains:

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;

public class SecondScreen extends AppCompatActivity {

TextView Email;
TextView Password;

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

Email = (TextView) findViewById(R.id.txt_email);


Password = (TextView) findViewById(R.id.txt_pwd);

Intent inIntent = getIntent();


String inEmail = inIntent.getStringExtra("var_email");
String inPwd = inIntent.getStringExtra("var_pwd");

Email.setText(inEmail);
Password.setText(inPwd);

}
}

File: layout_second_screen.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
tools:context=".SecondScreen">

<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:

Intent inIntent = getIntent();


String inEmail = inIntent.getStringExtra("var_email");
String inPwd = inIntent.getStringExtra("var_pwd");

9.4. Exercise 1
Suppose we have this activity:

106 
Learn Android in the University

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".MainActivity">

<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>

Write the code to pass the message to another activity.

9.5. Exercise 2
Suppose we have this activity:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:gravity="center"
android:orientation="vertical"
android:weightSum="1"
tools:context=".Register">

<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>

Write the code to pass the message to another activity.

108 
Learn Android in the University

Lesson 10. Activity Lifecycle


10.1. Content
An activity is the single screen in android. It is like window or frame of Java. In the activity, you can place all your UI
components or widgets in a single screen.

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.

10.2. Android Activity Lifecycle methods


Let's see the 7 lifecycle methods of android activity.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

109 
Learn Android in the University

10.3. Android Activity Lifecycle Example


It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the content
on the logcat.

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;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
110 
Learn Android in the University

Log.d(TAG, "onCreate: ");

Button btn = (Button) findViewById(R.id.btn1);

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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

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.

After a while, you will see onStop 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 click on the lifecycleactivity icon.

Now see on the logcat: onRestart, onStart and onResume methods are invoked.

114 
Learn Android in the University

If you see the emulator, application is started again.

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.

10.4. Switch between activities


We add another button on the MainActivity and create a second activity. Let's try to observe both 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;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
Log.d(TAG, "onCreate: ");

Button btn = (Button) findViewById(R.id.btn1);

116 
Learn Android in the University

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});

Button btnopen = (Button) findViewById(R.id.btn_open);

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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"

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;

public class SecondScreen extends AppCompatActivity {

private static final String TAG = "SecondActivity";

@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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondScreen">

<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

Lesson 11. Introduction to ListViews


11.1. Content
ListViews are used in almost every Android Application. They are truly essential to master. Here is a simple example of
how to get started with ListViews and add data to them to display in an Activity.

11.2. Java code


File: MainActivity.java

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;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

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

ListView list = (ListView) findViewById(R.id.theList);


Log.d(TAG, "onCreate: Started.");

ArrayList categories = new ArrayList<>();


categories.add("‫;)"شوارمة‬
categories.add("‫;)"مأكوالت‬
categories.add("‫;)"مشويات‬
categories.add("‫;)"عصيرات‬
categories.add("‫;)"ساخنة مشروبات‬
categories.add("‫;)"خبز‬

ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item_layout, categories);


list.setAdapter(adapter);

}
}
}

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<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">

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

<?xml version="1.0" encoding="utf-8"?>


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"
android:textColor="@color/colorPrimaryDark"
android:textAlignment="center"
android:gravity="center" />

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.

We add these views:

- EditView: to type a component like printer or scanner


124 
Learn Android in the University

- Button: to add the typed component to the list

File: layout_list_products.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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"
android:orientation="vertical"
tools:context=".ListProductsActivity">

<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

<?xml version="1.0" encoding="utf-8"?>


<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="‫"واحد عنصر مثال‬
android:textColor="#efe122"
android:textSize="20dp"
android:textStyle="bold"
android:gravity="center"
android:background="#000000"/>

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;

public class ListProductsActivity extends AppCompatActivity {

ArrayList products;
ArrayAdapter adapter;
ListView list;

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

list = (ListView) findViewById(R.id.thelist);

products = new ArrayList<>();

products.add("‫;)"كمبيوتر‬
products.add("‫;)"مفاتيح لوحة‬
products.add("‫;)"فأرة‬
products.add("‫;)"شاشة‬

adapter = new ArrayAdapter(this, R.layout.list_item_layout, products);


list.setAdapter(adapter);

}
}

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;

public class ListProductsActivity extends AppCompatActivity {


Button btn;
ArrayList products;
EditText EdProduct;
ArrayAdapter adapter;
ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_products);
126 
Learn Android in the University

btn =(Button) findViewById(R.id.btnadd);


EdProduct = (EditText) findViewById(R.id.product);

list = (ListView) findViewById(R.id.thelist);

products = new ArrayList<>();

products.add("‫;)"كمبيوتر‬
products.add("‫;)"مفاتيح لوحة‬
products.add("‫;)"فأرة‬
products.add("‫;)"شاشة‬

adapter = new ArrayAdapter(this, R.layout.list_item_layout, products);


list.setAdapter(adapter);

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

Lesson 12. OnItemClickListener for a ListView (display a message when


clicked)
12.1. Content
This is a lesson on how to add an OnItemClickListener to a ListView. We show you how to print out a Toast message when
clicking on a particular element in the list.

12.2. Java Code


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.AdapterView;
import android.view.View;
import android.widget.ListView;

import java.util.ArrayList;
import android.widget.Toast;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";


private ArrayAdapter adapter;

ArrayList categories = new ArrayList<>();

@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("‫;)"ساخنة مشروبات‬

adapter = new ArrayAdapter(this, R.layout.list_item_layout, categories);


list.setAdapter(adapter);

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();

Intent intent = new Intent(MainActivity.this, ProductActivity.class);


intent.putExtra("cat", categories.get(i).toString());
startActivity(intent);
128 
Learn Android in the University

}
});

}
}

File: activity_categories.xml

<?xml version="1.0" encoding="utf-8"?>


<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/theList"/>
</RelativeLayout>

12.3. Dialog
12.4. Use DialogFragment over AlertDialog:

 Since the introduction of API level 13:


the showDialog method from Activity is deprecated. Invoking a dialog elsewhere in code is not advisable
since you will have to manage the the dialog yourself (e.g. orientation change).
 Difference DialogFragment - AlertDialog
Are they so much different? From Android reference regarding DialogFragment:
A DialogFragment is a fragment that displays a dialog window, floating on top of its activity's window. This
fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the
dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on
the dialog.
 Other notes
 Fragments are a natural evolution in the Android framework due to the diversity of devices with different
screen sizes.
 DialogFragments and Fragments are made available in the support library which makes the class usable in
all current used versions of Android.

129 
Learn Android in the University

Lesson 13. Custom ListView with Multiple Columns


13.1. Content
In this lesson we'll build a custom List Adapter class for displaying objects in a ListView.

By the end of this lesson you will know how to:

- Display multiple columns in your ListView


- Build a ListAdapter class to display custom ListViews
- Build custom layouts for your ListView items

13.2. Java Code


File: Product.java

package com.android.listview2;

public class Product {


private int prod_id;
private String prod_name;
private double price;

// Constructor
public Product(int id, String name, double p) {
this.prod_id = id;
this.prod_name = name;
this.price = p;
}

public void setProdID(int id) {


this.prod_id = id;
}

public int getProdId() {


return this.prod_id;
}

public void setProdName(String name) {


this.prod_name = name;
}

public String getProdName() {


return this.prod_name;
}

public void setProdPrice(double p) {


this.price = p;
}

public double getProdPrice() {


return this.price;
}

}
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;

public class ProductListAdapter extends ArrayAdapter {


private static final String TAG = "ProductListAdapter";

private Context mContext;


private int mResource;

/**
* 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();

//Create the product object with the information


Product prod = new Product(id, name, price);

LayoutInflater inflater = LayoutInflater.from(mContext);


convertView = inflater.inflate(mResource, null);

TextView tvId = (TextView) convertView.findViewById(R.id.textView1);


TextView tvName = (TextView) convertView.findViewById(R.id.textView2);
TextView tvPrice= (TextView) convertView.findViewById(R.id.textView3);

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;

public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");

ListView mListView = (ListView) findViewById(R.id.listView);

//Create the Product objects


Product p1 = new Product(1,"‫صحن‬ ‫"صغير شوارما‬,5.00);
Product p2 = new Product(2,"‫صحن‬ ‫"كبير شوارما‬,10.00);
Product p3 = new Product(3,"‫نفر‬ ‫"مشكل مشوي‬,25.00);
Product p4 = new Product(4,"‫نفر‬ ‫"غنم لحم مشوي‬,25.00);
Product p5 = new Product(5,"‫نفر‬ ‫"دجاج مشوي‬,15.00);

//Add the Product objects to an ArrayList


ArrayList menuList = new ArrayList<>();
menuList.add(p1);
menuList.add(p2);
menuList.add(p3);
menuList.add(p4);
menuList.add(p5);

ProductListAdapter adapter = new ProductListAdapter(this, R.layout.adapter_view_layout,


menuList);
mListView.setAdapter(adapter);

}
}

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100">

<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

Lesson 14. ListView with Images and Text


14.1. Content
In this lesson we'll continue on from the previous ListView Task. We now add images to the ListView.

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.

Check out the details of the Library here: https://github.com/nostra13/Android-Universal-Image-Loader

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

Don't forget to add the images to your drawables folder.

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'

14.2. Java Code


File: Product.java

package com.android.listview2;

public class Product {


private int prod_id;
private String prod_name;
private double price;
private String imgUrl;

// 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;
}

public void setProdID(int id) {


this.prod_id = id;
}

public int getProdId() {


return this.prod_id;
}

public void setProdName(String name) {


this.prod_name = name;
}

public String getProdName() {


return this.prod_name;
}

public void setProdPrice(double p) {


this.price = p;
}

135 
Learn Android in the University

public double getProdPrice() {


return this.price;
}

public void setImgUrl(String imgPath) {


this.imgUrl = imgPath;
}

public String getImgUrl() {


return this.imgUrl;
}

}
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;

public class ProductListAdapter extends ArrayAdapter {


private static final String TAG = "ProductListAdapter";

private Context mContext;


private int mResource;
private int lastPosition = -1;

/**
* 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();

//get the products information


int id = ((Product)getItem(position)).getProdId();
String name = ((Product)getItem(position)).getProdName();
double price = ((Product)getItem(position)).getProdPrice();
String imgUrl = ((Product)getItem(position)).getImgUrl();

//create the view result for showing the animation


final View result;

//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;
}

Animation animation = AnimationUtils.loadAnimation(mContext,


(position > lastPosition) ? R.anim.load_down_anim : R.anim.load_up_anim);
result.startAnimation(animation);
lastPosition = position;

holder.id.setText(Integer.toString(id));
holder.name.setText(name);
holder.price.setText(Double.toString(price));

//create the imageloader object


ImageLoader imageLoader = ImageLoader.getInstance();
;
int defaultImage =
mContext.getResources().getIdentifier("@drawable/image_failed",null,mContext.getPackageName());

//create display options


DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();

//download and display image from url


imageLoader.displayImage(imgUrl, holder.image, options);

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();

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(


mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).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;

public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");

ListView mListView = (ListView) findViewById(R.id.listView);

//Create the Product objects


Product p1 = new Product(1,"‫"صغير شوارما صحن‬,5.00, "drawable://" + R.drawable.shawarma);
Product p2 = new Product(2,"‫"كبير شوارما صحن‬,10.00, "drawable://" + R.drawable.shawarma1);
Product p3 = new Product(3,"‫"مشكل مشوي نفر‬,25.00, "drawable://" +
R.drawable.mishwimshakal);
Product p4 = new Product(4,"‫"غنم لحم مشوي نفر‬,25.00, "drawable://" + R.drawable.ghanam);
Product p5 = new Product(5,"‫"حاشي لحم مشوي نفر‬,25.00, "drawable://" + R.drawable.hashi);
Product p6 = new Product(6,"‫"دجاج مشوي نفر‬,15.00, "drawable://" + R.drawable.dajaj);
Product p7 = new Product(7,"‫"فول‬,3.00, "drawable://" + R.drawable.foul);
Product p8 = new Product(8,"‫"عدس‬,3.00, "drawable://" + R.drawable.adas);
Product p9 = new Product(9,"‫"قشطة معصوب‬,9.00, "drawable://" + R.drawable.masoub);
Product p10 = new Product(10,"‫"عريكة‬,10.00, "drawable://" + R.drawable.arika);
Product p11 = new Product(11,"‫"تميس خبز‬,1.00, "drawable://" + R.drawable.tamis);

138 
Learn Android in the University

Product p12 = new Product(12,"‫"شامي خبز‬,1.50, "drawable://" + R.drawable.shami);


Product p13 = new Product(13,"‫"برتقال عصير‬,3.00, "drawable://" + R.drawable.brtoukal);

//Add the Product objects to an ArrayList


ArrayList menuList = new ArrayList<>();
menuList.add(p1);
menuList.add(p2);
menuList.add(p3);
menuList.add(p4);
menuList.add(p5);
menuList.add(p6);
menuList.add(p7);
menuList.add(p8);
menuList.add(p9);
menuList.add(p10);
menuList.add(p11);
menuList.add(p12);
menuList.add(p13);

ProductListAdapter adapter = new ProductListAdapter(this, R.layout.adapter_view_layout,


menuList);
mListView.setAdapter(adapter);

}
}

File: load_down_anim.xml

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="@android:anim/decelerate_interpolator">
<translate
android:fromXDelta="0%" android:toXDelta="0%"
android:fromYDelta="-100%" android:toYDelta="0%"
android:duration="400" />
</set>

File: load_up_anim.xml

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="@android:anim/decelerate_interpolator">
<translate
android:fromXDelta="0%" android:toXDelta="0%"
android:fromYDelta="100%" android:toYDelta="0%"
android:duration="400" />
</set>

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100">

<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

Lesson 15. CardView


15.1. Content
In this lesson we go over an introduction to CardViews. CardViews are mainly used in ListViews and RecyclerViews. If you
were building an app similar to Instragram and YouTube, CardViews would be perfect. Anything where you have repeating
posts of pictures with short descriptions below them.

15.2. Display a card container


Create new Project and add the following dependency

implementation 'com.android.support:cardview-v7:24.0.+'

Add a picture in the folder res/drawable:

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;

public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";

private ImageView mCardImage;

142 
Learn Android in the University

private TextView mCardTitle;

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

mCardImage = (ImageView) findViewById(R.id.cardImage);


mCardTitle = (TextView) findViewById(R.id.cardTitle);

int imageResource = getResources().getIdentifier("@drawable/drawn_mosque_kaaba", null,


this.getPackageName());
mCardImage.setImageResource(imageResource);

mCardTitle.setText("Kaaba");

}
}
File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".MainActivity">

<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

15.3. CardViews displayed in ListView


In this Android Task we go over how to use CardViews in a ListView. We use the "ViewHolder Build-Pattern" so scrolling
the ListView doesn't cause any lagging. An alternate way to do this would be to use a RecyclerView.

Add the CardView Dependency and the Universal Image Loader Dependency:

//cardview
compile 'com.android.support:cardview-v7:24.0.+'

//Universal Image Loader


compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
144 
Learn Android in the University

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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<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;

public class Card {


private String imgURL;
private String title;

public Card(String imgURL, String title) {


this.imgURL = imgURL;
this.title = title;
}

public String getImgURL() {


return imgURL;
}

public void setImgURL(String imgURL) {


this.imgURL = imgURL;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}
}

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

public class CustomListAdapter extends ArrayAdapter<Card> {

private static final String TAG = "CustomListAdapter";

private Context mContext;


private int mResource;
private int lastPosition = -1;

/**
* 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) {

//sets up the image loader library


setupImageLoader();

//get the persons information


String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();

try{

//create the view result for showing the animation


final View result;

//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;
}

Animation animation = AnimationUtils.loadAnimation(mContext,


(position > lastPosition) ? R.anim.load_down_anim : R.anim.load_up_anim);
result.startAnimation(animation);
lastPosition = position;

holder.title.setText(title);

//create the imageloader object


ImageLoader imageLoader = ImageLoader.getInstance();

int defaultImage =
mContext.getResources().getIdentifier("@drawable/image_failed",null,mContext.getPackageName());

//create display options


DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();

//download and display image from url


imageLoader.displayImage(imgUrl, holder.image, options);

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();

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(


mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).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;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";


private ListView mListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
mListView = (ListView) findViewById(R.id.listView);

ArrayList<Card> list = new ArrayList<>();

list.add(new Card("drawable://" + R.drawable.jad, "Makka Jeddah"));


list.add(new Card("drawable://" + R.drawable.kab, "Kaaba"));
list.add(new Card("drawable://" + R.drawable.madina, "Madina"));
list.add(new Card("drawable://" + R.drawable.makka1, "Makkah"));
list.add(new Card("drawable://" + R.drawable.room, "Room"));
list.add(new Card("drawable://" + R.drawable.ryadh, "Ryadth"));
list.add(new Card("drawable://" + R.drawable.train, "Train"));

CustomListAdapter adapter = new CustomListAdapter(this, R.layout.activity_main, list);


mListView.setAdapter(adapter);

}
}
Don't forget to save some picture in the drawable folder.

149 
Learn Android in the University

Lesson 16. Implementing Splash Screen


16.1. Content
A splash screen is a screen that shows up when we launch the app. Splash Screen is very common term and it is required
for all the application. The idea behind this is, to show user a welcome screen while your application is loading. In this
android splash screen example we are going to learn how do we implement a splash screen in our application.

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.

Now let’s just create our android project using an EmptyActivity.

Once your project is loaded, first we will design our Splash Screen.

16.2. Designing Splash Screen


For designing the Splash Screen we will create an empty activity.

Here we are going to design our Splash Screen. So inside the file put the following code:

File: activity_splashscreen.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.vk.BTcar.SplashScreen">

<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;

public class SplashScreen extends AppCompatActivity {

@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.

Inside AndroidManifest.xml, change the Launcher to the SplashScreen Activity.

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

Lesson 17. Making Custom AlertDialog


17.1. Content
In this lesson we will see an Android Custom Dialog Example.

Again the first thing is creating a new Android Studio project.

17.2. Java Code


File: button_background.xml

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<stroke android:width="2dp" android:color="@color/colorPrimary" />

<solid android:color="@android:color/transparent" />

<corners android:bottomLeftRadius="6dp" android:bottomRightRadius="6dp"


android:topLeftRadius="6dp" android:topRightRadius="6dp" />
</shape>
</item>
</selector>

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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<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

android:text="Here the message you want to display...."


android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
<Button
android:id="@+id/buttonOk"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:background="@drawable/button_background"
android:text="Ok"
android:textColor="@color/colorPrimary" />

</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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<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

public class MainActivity extends AppCompatActivity {

@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) {

//calling this method to show our android custom alert dialog


showCustomDialog();
}
});
}

private void showCustomDialog() {


//before inflating the custom alert dialog layout, we will get the current activity
viewgroup
ViewGroup viewGroup = findViewById(android.R.id.content);
//then we will inflate the custom alert dialog xml that we created
View dialogView = LayoutInflater.from(this).inflate(R.layout.the_dialog, viewGroup, false);
//Now we need an AlertDialog.Builder object
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//setting the view of the builder to our custom view that we already inflated
builder.setView(dialogView);
//finally creating the alert dialog and displaying it
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

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

Lesson 18. How to use Fragments


18.1. Content
In this lesson, we go over how to use Fragments in Android. If you follow this lesson you'll have a template you can use in
all your applications.

18.2. Navigate between fragments


Fragments:

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;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");

mViewPager = (ViewPager) findViewById(R.id.containter);


//setup the pager
setupViewPager(mViewPager);

private void setupViewPager(ViewPager viewPager){


SectionsStatePagerAdapter adapter = new
SectionsStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), "Fragment1");
adapter.addFragment(new Fragment2(), "Fragment2");
adapter.addFragment(new Fragment3(), "Fragment3");
viewPager.setAdapter(adapter);
}

public void setViewPager(int fragmentNumber){


mViewPager.setCurrentItem(fragmentNumber);
}
}

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
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="univ.com.fragements.MainActivity">

<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;

public class SectionsStatePagerAdapter extends FragmentStatePagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();


private final List<String> mFragmentTitleList = new ArrayList<>();

public SectionsStatePagerAdapter(FragmentManager fm) {


super(fm);
}

public void addFragment(Fragment fragment, String title){


mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@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.

For example, Fragment1looks like this:

public class Fragment1 extends Fragment {


. . .

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
final Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment1_layout, container, false);


. . .
. . .

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;

public class Fragment1 extends Fragment {


private static final String TAG = "Fragment1";

private Button btnNavFrag1;


private Button btnNavFrag2;
private Button btnNavFrag3;
private Button btnNavSecondActivity;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
final Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment1_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();
((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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9595f5"
android:orientation="vertical">

<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;

public class Fragment2 extends Fragment {


private static final String TAG = "Fragment1";

private Button btnNavFrag1;


private Button btnNavFrag2;
private Button btnNavFrag3;
private Button btnNavSecondActivity;

@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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#a5f792"
android:orientation="vertical">

<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;

public class Fragment3 extends Fragment {


private static final String TAG = "Fragment1";

private Button btnNavFrag1;


private Button btnNavFrag2;
private Button btnNavFrag3;
private Button btnNavSecondActivity;

@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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7ee90"
android:orientation="vertical">

<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;

public class SecondActivity extends AppCompatActivity {


private static final String TAG = "SecondActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity_layout);

Log.d(TAG, "onCreate: started.");

}
}

File: second_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ed68e2">

<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

android:text="This is the SecondActivity Layout"


android:layout_centerHorizontal="true"
android:textSize="25sp"/>

</RelativeLayout>

167 
Learn Android in the University

Lesson 19. Customizing The Action Bar: add Menu


19.1. Content

19.2. Create the menu


Create new folder in resources called menu. And create main_menu.xml file:

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:title="Settings" android:id="@+id/settings"></item>


<item android:title="About" android:id="@+id/about"></item>
</menu>

19.3. Slect Menu Item


MainActivity.java

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;

public class MainActivity extends AppCompatActivity {

@Override
public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater menuInflater = getMenuInflater();


menuInflater.inflate(R.menu.main_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

Lesson 20. Bottom Navigation Android Example using Fragments


20.1. Content
In this lesson we will see how we combine the Bottom Navigation and Fragments. Bottom Navigation Bar always stays at
the bottom of the application and provides navigation between the views.

Below you can see a Bottom Navigation.

20.2. Using Bottom Navigation in Android


It is very easy, you can create a Bottom Navigation Activity in your project by following ways.

#1 you just need to use <android.support.design.widget.BottomNavigationView />, if you want to do it in XML.

#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.

Bottom Navigation Android Activity

#3 While creating an Android Project you can select Bottom Navigation Activity from the template.
170 
Learn Android in the University

Bottom Navigation Android Activity from Templates

20.3. Bottom Navigation Android Example


Now lets see everything in an Android Project.

Defining Colors and Strings


We have created a project named BottomNavigationExample using a Bottom Navigation Activity. You can choose Empty
Activity, it will not make any difference.

Now first, we will define the colors. You can change the colors to anything you want. So define the following in the
colors.xml

<?xml version="1.0" encoding="utf-8"?>


<resources>
<color name="colorPrimary">#278be3</color>
<color name="colorPrimaryDark">#0f5998</color>
<color name="colorAccent">#4075a2</color>
<color name="colorNavIcon">#dae9f6</color>
<color name="colorNavText">#01294b</color>
</resources>

Define the following strings in the file strings.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

Customizing Bottom Navigation View


Modify the file activity_main.xml as shown below:

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.simplifiedcoding.bottomnavigationexample.MainActivity">

<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>

Remember for <android.support.design.widget.BottomNavigationView />we can use the following properties:

o app:itemIconTint : for defining the Item Icon color.


o app:itemTextColor : for defining the Item Text Color.
o android:background : for defining the Bottom Navigation View background.
o app:menu : for defining the menu that we need to display in the Bottom Navigation View.

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.

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">

<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.

Bottom Navigation Android 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.

Create fragment_home.xml, fragment_dashboard.xml, fragment_notifications.xml and fragment_profile.xml

All the files will have the following code in it.

File: fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<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

Now create java classes named, HomeFragment.java, DashboardFragment.java, NotificationsFragment.java and


ProfileFragment.java.

Each file will contain the following code in it.

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;

public class HomeFragment extends Fragment {


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard

174 
Learn Android in the University

return inflater.inflate(R.layout.fragment_home, null);


}
}

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.

private boolean loadFragment(Fragment fragment) {


//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}

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);

//loading the default fragment


loadFragment(new HomeFragment());

//getting bottom navigation view and attaching the listener


BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
}

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.

Now, we need to implement OnNavigationItemSelectedListener interface in the activity class.

//implement the interface OnNavigationItemSelectedListener in your activity class


public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {

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;

//implement the interface OnNavigationItemSelectedListener in your activity class


public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {

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

//loading the default fragment


loadFragment(new HomeFragment());

//getting bottom navigation view and attaching the listener


BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;

switch (item.getItemId()) {
case R.id.navigation_home:

176 
Learn Android in the University

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);
}

private boolean loadFragment(Fragment fragment) {


//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
Now, you can try running the application.

177 
Learn Android in the University

Bottom Navigation Android Example

Now you can design your fragments as you want, you can create some complex User Interface there.

Lesson 21. Android Toolbar Example


21.1. Content
In this lesson, we will be explaining how to use Toolbar in the application.

What is Toolbar in Android?


The toolbar was introduced from Android Lollipop when Material Design came into existence. Before Toolbar we were
using ActionBar, the position of ActionBar was fix at the top of the screen. But in case of Toolbar, it is more flexible; you
can place Toolbar anywhere in the Activity. The toolbar is useful for displaying App Icon, Title, Navigation Menu, etc.

You can see an example of the toolbar in below image.

Android Toolbar Example

21.2. Android Toolbar Example


Let’s create a new Android Project called Toolbar Example.

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>

So we need to modify the above XML thing as below.

<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>

Creating Toolbar Layout


Create toolbar inside activity_main.xml as shown below:

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<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">

<!--

put your activity content here


You can change the layout to anything you want
right now it is a linear layout

-->

</LinearLayout>
</RelativeLayout>

The above XML will generate a toolbar in your activity.

179 
Learn Android in the University

Setting Title for the Toolbar


Inside MainActivity.java, add a title for the Toolbar:

package com.android.toolbarexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

//setting the title


toolbar.setTitle("The Toolbar");

//placing toolbar in place of actionbar


setSupportActionBar(toolbar);
}
}
Now, execute your application and you will see the following output.

180 
Learn Android in the University

21.3. Setting up a Menu on the Toolbar


Creating a Menu

Many times you see a menu on the right of the toolbar. Now let’s see how you can create this.

First create a folder named menu inside res.

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

Inside the menu.xml file write the following code.

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<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>
Here, we have only three menu items but if you need you can add as many menu
items as you want.

Adding Menu to Toolbar

We will do it inside MainActivity.java. Just add the following method inside


MainActivity class.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}

Now you will see the menu in your application.

183 
Learn Android in the University

Handling Menu Clicks

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.

Setting up a Search on the Toolbar


184 
Learn Android in the University

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.

Adding a Search Icon

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.

Adding Search Menu

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

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<!-- our search option -->


<item
android:id="@+id/menuSearch"
android:icon="@drawable/icon_search"
android:orderInCategory="100"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />

<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) {

MenuInflater menuInflater = getMenuInflater();


menuInflater.inflate(R.menu.menu, menu);

//getting the search view from the menu


MenuItem searchViewItem = menu.findItem(R.id.menuSearch);

//getting search manager from systemservice


SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

//getting the search view


final SearchView searchView = (SearchView) searchViewItem.getActionView();

//you can put a hint for the search input field


searchView.setQueryHint("Search Tutorials...");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

//by setting it true we are making it iconified


//so the search input will show up after taping the search iconified
//if you want to make it visible all the time make it false
searchView.setIconifiedByDefault(true);

//here we will get the search query


searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {

//do the search here


return false;
}

@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

Lesson 22. Android Navigation Drawer Example using Fragments


22.1. Content
Here is another lesson for one of the most common things in any android application, navigation drawer.

22.2. Java Code


Creating a new project

So first we will create a new project. And select the navigation drawer activity.

187 
Learn Android in the University

Navigation Drawer Activity

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.

Customising Navigation Drawer Menus

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).

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_menu1"
android:icon="@mipmap/ic_launcher"
android:title="Menu 1" />
<item
android:id="@+id/nav_menu2"
android:icon="@mipmap/ic_launcher"
android:title="Menu 2" />
<item
android:id="@+id/nav_menu3"
android:icon="@mipmap/ic_launcher"
android:title="Menu 3" />

</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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"

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>

Removing the Floating Action Button

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

<?xml version="1.0" encoding="utf-8"?>


<android.support.design.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
tools:context="net.simplifiedcoding.navigationdrawerexample.MainActivity">

<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);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);


ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);


navigationView.setNavigationItemSelectedListener(this);

//add this line to display menu1 when the activity is loaded


displaySelectedScreen(R.id.nav_menu1);
}

Creating Screens for Navigation Menus using Fragment

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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="net.simplifiedcoding.navigationdrawerexample.MainActivity"
tools:showIn="@layout/app_bar_main">

<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

Now we will create the Fragments.

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;

public class Menu1 extends Fragment {

@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.

Switching Between Fragments on Navigation Drawer Menu Selection

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) {

//calling the method displayselectedscreen and passing the id of selected menu


displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}

private void displaySelectedScreen(int itemId) {


//creating fragment object
Fragment fragment = null;

//initializing the fragment object which is selected


switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);


drawer.closeDrawer(GravityCompat.START);
}

192 
Learn Android in the University

Here we removed the previous if else conditions and added our own according to the customised menu ids.

So the final code for MainActivity.java is

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;

public class MainActivity extends AppCompatActivity


implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);


ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);


navigationView.setNavigationItemSelectedListener(this);

//add this line to display menu1 when the activity is loaded


displaySelectedScreen(R.id.nav_menu1);
}

@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);
}

private void displaySelectedScreen(int itemId) {

//creating fragment object


Fragment fragment = null;

//initializing the fragment object which is selected


switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}

//replacing the fragment


if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);


drawer.closeDrawer(GravityCompat.START);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

//calling the method displayselectedscreen and passing the id of selected menu


displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}

194 
Learn Android in the University

Lesson 23. Android TabLayout Example using ViewPager and


Fragments
23.1. Content
One of the component of material design is TabLayout. So in this lesson we will see how we can implement it in our
android application.

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.

23.2. Android Tablayout Example


Open Android Studio and create a new project AndroidTabLayout.

Adding Design Support to our Project

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.

Select design and click on ok.

196 
Learn Android in the University

Creating Layouts for the Tab Views

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

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<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;

//Our class extending fragment


public class Tab1 extends Fragment {

//Overriden method onCreateView


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {

//Returning the layout file after inflating


//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.tab1, container, false);
}
}

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

Creating a pager adapter

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 {

//integer to count number of tabs


int tabCount;

//Constructor to the class


public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}

//Overriding method getItem


@Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}

//Overriden method getCount to get the number of tabs


@Override
public int getCount() {
return tabCount;
}
}

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>

Creating TabLayout and ViewPager

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">

<!-- our toolbar -->


<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<!-- our tablayout to display tabs -->


<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<!-- View pager to swipe views -->


<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>

</LinearLayout>

In the MainActivity.java, add the code below:

200 
Learn Android in the University

//Implementing the interface OnTabSelectedListener to our MainActivity


//This interface would help in swiping views
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{

//This is our tablayout


private TabLayout tabLayout;

//This is our viewPager


private ViewPager viewPager;

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) {

Now come inside onCreate() and write the following code.

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

//Adding toolbar to the activity


Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

//Initializing the tablayout


tabLayout = (TabLayout) findViewById(R.id.tabLayout);

//Adding the tabs using addTab() method


tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);

//Creating our pager adapter


Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());

//Adding adapter to pager


viewPager.setAdapter(adapter);

//Adding onTabSelectedListener to swipe views


tabLayout.setOnTabSelectedListener(this);
}
201 
Learn Android in the University

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());
}

So the final code for MainActivity.java would be.

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;

//Implementing the interface OnTabSelectedListener to our MainActivity


//This interface would help in swiping views
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{

//This is our tablayout


private TabLayout tabLayout;

//This is our viewPager


private ViewPager viewPager;

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

//Adding toolbar to the activity


Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

//Initializing the tablayout


tabLayout = (TabLayout) findViewById(R.id.tabLayout);

//Adding the tabs using addTab() method


tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);

//Creating our pager adapter


Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());

//Adding adapter to pager


viewPager.setAdapter(adapter);

//Adding onTabSelectedListener to swipe views


tabLayout.setOnTabSelectedListener(this);
}

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

- Android App Development – AbhiAndroid (http://abhiandroid.com )

Websites

- Official Android Website: https://developers.google.com/training/android/

- https://codingwithmitch.com

- https://www.simplifiedcoding.net

- https://www.tutorialspoint.com/android/

- https://www.tutlane.com/tutorial/android

204 

You might also like