Android - Module 1 and 2
Android - Module 1 and 2
- Shweta Waghmare,TIMSCDR
Topics
Creating an android application, Creating the activity, Design user interface with
Views, Working with intents, fragments, services and different types of layouts
components. Displaying picture and menus using views.
Self-Learning Topics:
Steps:
● Check java is installed or not: java -version on cmd
● If not install the Java
● Download android studio : https://developer.android.com/studio
● Install it.
● How to Install Android Studio on Windows 10:
https://www.youtube.com/watch?v=0zx_eFyHRU0
With Screenshot :
https://www.c-sharpcorner.com/article/how-to-download-and-install-android-studio-in-wi
ndows-10/
What is HAXM….
https://stackoverflow.com/questions/32011025/cant-install-intel-haxm-for-and
roid-studio-error-x86-emulation-currently-requi
Creating an android application
Official site(syllabus)
https://developer.android.com/codelabs/build-your-first-android-app#2
Step 1: Create a new project
1. Open Android Studio.
2. In the Welcome to Android Studio dialog, click Start a new Android Studio
project.
3.Select Basic
Activity (not
the default).
Click Next.
4. Give your
application a name
such as My First App.
5. Make sure the
Language is set to
Java
6. Leave the defaults
for the other fields.
7. Click Finish.
Step 2: Get your screen set up
and layout
1. Manifests Folder
2. Java Folder
3. res (Resources) Folder
○ Drawable Folder
○ Layout Folder
○ Mipmap Folder
○ Values Folder
4. Gradle Scripts
Manifests Folder
Manifests folder contains AndroidManifest.xml for our creating the android application.
This file contains information about our application such as the Android version,
metadata, states package for Kotlin file, and other application components. It acts as an
intermediary between android OS and our application.
The Java folder contains all the java and Kotlin source code (.java) files that we
create during the app development, including other Test files. If we create any new
project using Kotlin, by default the class file MainActivity.kt file will create
automatically under the package name “com.geeksforgeeks.myfirstkotlinapp” as
shown below
Resource (res) folder
The resource folder is the most important folder because it contains all the non-code
sources like images, XML layouts, and UI strings for our android application.
Gradle Scripts folder
Gradle means automated build system and it contains a number of files that are
used to define a build configuration that can be applied to all modules in our
application. In build.gradle (Project) there are build scripts and in build.gradle
(Module) plugins and implementations are used to build configurations that can be
applied to all our application modules.
Task: Explore the layout editor
Find and open the layout folder (app > res > layout) on the left side in the Project panel.
Layouts are defined in XML. The layout editor lets you define and modify your layout
either by coding XML or by using the interactive visual editor.
Step 1: Firstly, click on app > res > layout > Right Click on layout. After that
Select New > Activity and choose your Activity as per requirement.
Step 2: After that Customize the Activity in Android Studio. Enter the “Activity
Name” and “Package name” in the Text box and Click on Finish button.
Step 3: After that your new Activity in Layout will be created. Your XML Code is
in Text and your Design Output is in Design.
Design user interface with Views
Designing User Interface With Views In Android App
What is View :
The view is the component which Android provides us to design the layouts of
the app. So, we can understand view as a rectangular area which is going to
contain some element inside it.
TimePicker :
https://www.tutorialspoint.com/android/android_timepicker_control.htm
https://www.javatpoint.com/android-timepicker-examplev
Spinner view :
A Spinner is a type of view that hold items in form of a dropdown menu available
for user selection. It creates a menu with multiple options where a user can
select any one option. Following is an example of a spinner.
What's the difference between Spinner and ListView?
Both ListView and Spinner looks very similar. But they differ from each other.
Spinners provide a quick way to select one value from a given set of values and in the
default state, a spinner only shows the currently selected value. When you touch(tap on)
the spinner, it displays a dropdown menu with all other available values(options), from
which the user can select a new one.
ListView, on the other hand, is a view group that displays a list of scrollable items. The list
items are automatically inserted to the list using an Adapter that pulls content from a data
source such as an array or database table and converts each dataitem into a view that is
placed in the list.
Therefore, a Spinner and ListView differs in the way they appear and in their usage too. If
you want to select only one value from a set of options then you should use a Spinner. If
you want to display a list of data then use a list view.
How does a Spinner works?
Define the data source: A data source can be a list, an array, a JSON data or data
coming from a database.
String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"};
onItemSelected()
This method has 4 parameters:
● AdapterView av: It's the Spinner view that you have used.
● View v: It defines the TextView inside the spinner that was clicked.
● int position: It tells the position of the item that was clicked in the Spinner. The index or
the position starts from 0.
● long id: It gives the row id of the item clicked in the Spinner. This parameter is mainly
used when dealing with databases in Android.
onNothingSelected()
This method has only 1 parameter:
AdapterView av: It's the Spinner view that you have used. This method is
called whenever the currently selected item is removed from the list of
available items in the Spinner. If the adapter is modified such that the
currently selected item is no longer available, then this method will be called.
This method may be used so that you can set which item will be selected
when the previous item is no longer available. This prevents the spinner from
automatically selecting the next item in the list.
If mySpinner is an instance of a Spinner view then, following is how we can
implement the above listeners:
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
// If an option is removed then what to do
// or anything else
}
});
Working with intents, fragments, services
What is fragment and intents?
Intent, you can think of intention to do some work. It can be either go from
one activity to another activity, send email, open some links and so on.
Fragment is just like part of those activities. To make it simple you can think of
activities as full website page whereas fragment as a part of that website page
Android Intent is the message that is passed between components such as
activities, content providers, broadcast receivers, services etc.
It is generally used with startActivity() method to invoke activity, broadcast
receivers etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as
the intention to do action.
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides
information of available components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external
class to be invoked.
Intent
Intent :
● Start an activity
● Start a service
● Delivery a broadcast
● Display a Webpage etc.
Activities
}
Services
A service is a component that runs in the background to perform long-running
operations.
}
Content Providers
A content provider component supplies data from one application to others on
request. Such requests are handled by the methods of the ContentResolver class.
The data may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform
transactions.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}
Additional Components
Fragments : Represents a portion of user interface in an Activity.
Views : UI elements that are drawn on-screen including buttons, lists forms
etc.
Layouts : View hierarchies that control screen format and appearance of the
views.
Intents : Messages wiring components together.
Resources : External elements, such as strings, constants and drawable
pictures.
Manifest : Configuration file for the application.
Activities, Fragments and Intents
Activity is an application component that gives a user interface where the user
can interact.
Intent, you can think of intention to do some work. It can be either go from one
activity to another activity, send email, open some links and so on.
Fragment is just like part of those activities. To make it simple you can think of
activities as full website page whereas fragment as a part of that website page.
Activities :
● Activity is one of the most important component for any android app.
● Activities are the User Interface (UI) screens which user see.
● All your activities must be declared in the manifest file, with their
attributes.
Every activity has different functions
throughout its life, onCreate(),
onStart(), onResume(), onPause(),
onStop(), onRestart(), onDestroy().
Intents :
Intent is one of the most important and most used app component of an
android application.
Using Intents, you call to other app components or to other activity or also call
other applications on your phone.
Intents are two types:
Explicit Intents where you call another activity or something with a class name.
For instance, you can call another activity when some action happened in one
activity. So you here explicitly specifies which activity to call.
Implicit Intents where we do not specify a class name but specify some sort of
action, which can be handled by some other inbuilt apps or some other apps.
For instance, you may want to open a camera, showing a map, sending emails
etc. Here you don’t directly call camera app or map app, you will just specify the
action.
Fragment
Android Fragment is the part of activity, it is also known as sub-activity. There can
be more than one fragment in an activity. Fragments represent multiple screen
inside one activity.
Android fragment lifecycle is affected by activity lifecycle because fragments are
included in activity.
Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.
The FragmentManager class is responsible to make interaction between fragment
objects.
Refer for Life Cycle : https://www.javatpoint.com/android-fragments
Different types of layouts components
https://www.tutorialspoint.com/andr
oid/android_user_interface_layouts.
htm
Layout :
● A layout defines the structure for a user interface in your app, such as in an activity.
● All elements in the layout are built using a hierarchy of View and ViewGroup objects.
● A View usually draws something the user can see and interact with.
● Whereas a ViewGroup is an invisible container that defines the layout structure for View and other
ViewGroup
● The View objects are usually called "widgets" and can be one of many subclasses, such as Button or
TextView.
● The ViewGroup objects are usually called "layouts" can be one of many types that provide a
Inside Activity:
setContentView(R.layout.rainbow);
Important Linear Layout Properties and Attributes
Some specific attributes apply to linear layouts. Some of the most important attributes you’ll use with
linear layouts include:
● The orientation attribute (required), which can be set to vertical or horizontal (class: LinearLayout)
● The gravity attribute (optional), which controls how all child controls are aligned and displayed
within the linear layout (class: LinearLayout)
● The layout_weight attribute (optional, applied to each child control) specifies each child control’s
relative importance within the parent linear layout (class: LinearLayout.LayoutParams)
Table Layout
In android, TableLayout is a ViewGroup
subclass that is used to display the child View
elements in rows and columns.
Similarly, the orientation of the GridLayout may optionally be defined via the
android:orientation property. The following example XML declares a 2 x 2 GridLayout
configuration in horizontal orientation:
● A view can be placed within a specific cell by specifying the intersecting row and column number of the
destination cell. The following Button view will be placed in the cell and row 1, column 2 of the parent
GridLayout:
<Button
android:id="@+id/button5"
android:layout_column="2"
android:layout_row="1"
android:layout_gravity="left|top"
android:text="Button" />
● rowSpan or colspan ?
Frame Layout
Frame Layout is designed to block out an area on the screen to display a single item.
Generally, FrameLayout should be used to hold a single child view, because it can be difficult
to organize child views in a way that's scalable to different screen sizes without the children
overlapping each other.
Displaying picture and menus using views.
Android Gallery
Android Gallery is a widget. Unfortunately, this is deprecated in API 16. This view shows
items in a horizontal, centrally locked pattern. By default, Theme_galleryItemBackground
is used as background for each view which is given to the gallery via Adapter.
Gallery should use LayoutParams as type of layout parameters supplied to the views.
LayoutParams of views tell the parent view about their placing or position in respective
views.
- Shweta Waghmare,TIMSCDR
Topics
Module: Basic Controls and UI Components
Text view, Radio button, Checkbox, Image Button, Edit Text, Slider and other
controls
● TextView ● ProgressBar
● EditText ● Spinner
● Button ● TimePicker
● ImageButton ● DatePicker
● ToggleButton ● SeekBar
● RadioButton ● AlertDialog
● RadioGroup ● Switch
● CheckBox
● RatingBar
● AutoCompleteTextView
Application components
Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
Activities : They dictate the UI and handle the user interaction to the smart phone screen
Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves
and re-enters the activity. For example, if you're building a streaming video player, you might pause the
video and terminate the network connection when the user switches to another app. When the user
returns, you can reconnect to the network and let the user resume the video from the same spot.
For example, good implementation of the lifecycle callbacks can help your app avoid the following:
● Crashing if the user receives a phone call or switches to another app while using your app.
● Consuming valuable system resources when the user is not actively using it.
● Losing the user's progress if they leave your app and return to it at a later time.
● Crashing or losing the user's progress when the screen rotates between landscape and portrait
orientation.
To navigate transitions between
stages of the activity lifecycle, the
Activity class provides a core set of
six callbacks: onCreate(), onStart(),
onResume(), onPause(), onStop(),
and onDestroy(). The system
invokes each of these callbacks as
the activity enters a new state.
onPause()
Called as part of the activity lifecycle when the user no longer actively interacts with the
activity, but it is still visible on screen. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A. B will not
be created until A's onPause() returns, so be sure to not do anything lengthy here.
onStop()
● When Activity is in background then onPause() method will execute. After a millisecond of
that method next onStop() method will execute.
● Means here also Activity is not visible to user when onStop() executed.
● We will use onStop() method to stop Api calls etc. This onStop() method will
clean up all your activities resources.
MainActivity.Java
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle", "onStart invoked"); @Override
} protected void onRestart() {
super.onRestart();
Log.d("lifecycle", "onRestart invoked");
@Override
}
protected void onResume() {
super.onResume(); @Override
Log.d("lifecycle", "onResume invoked"); protected void onDestroy() {
} super.onDestroy();
Log.d("lifecycle", "onDestroy invoked");
@Override }
protected void onPause() {
super.onPause();
Log.d("lifecycle", "onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle", "onStop invoked");
}
Linear Layout
LinearLayout is the most basic layout in android studio, that aligns all the children
sequentially either in a horizontal manner or a vertical manner by specifying the
android:orientation attribute.
If one applies android:orientation=”vertical” then elements will be arranged one after
another in a vertical manner and If you apply android:orientation=”horizontal” then
elements will be arranged one after another in a horizontal manner.
Practical - 2 : Design the following
User Interface using Linear Layout.
Relative Layout
Android RelativeLayout enables you to specify how child views are positioned relative to each other. The
position of each view can be specified as relative to sibling elements or relative to the parent.
To arrange them in a proper order we need to use the relative layout. To arrange them we need some
advanced properties. Basically, we use layout_width, layout_height, layout_text properties while
creating an application using the linear layout. But we need some more advanced properties which are
supported by relative layout. There are so many properties that are supported by relative layout. some
of the most used properties are listed below
● layout_alignParentTop
● layout_alignParentBottom
● layout_alignParentRight
● layout_alignParentLeft
● layout_centerHorozontal
● layout_centerVertical
● layout_above
● layout_below
Practical - 3 : Design the
following User Interface using
Relative Layout.
Table Layout
Android TableLayout going to be arranged groups of views into rows
and columns. You will use the <TableRow> element to build a row in
the table. Each row has zero or more cells; each cell can hold one
View object.
TableLayout containers do not display border lines for their rows,
columns, or cells.
Practical - 4 Design the following
screen.
Frame Layout
Android Framelayout is a ViewGroup subclass that is used to specify the
position of multiple views placed on top of each other to represent a single
view screen.
Generally, we can say FrameLayout simply blocks a particular area on the screen
to display a single view. Here, all the child views or elements are added in stack
format means the most recently added child will be shown on the top of the
screen.
But, we can add multiple children’s views and control their positions only by
using gravity attributes in FrameLayout.
Practical - 5 Design a screen
which displays the frame image
and write a quote on that.
Practical - 7 Write a program to demonstrate radio buttons and checkboxes, Toggle button,Image
button.
● Radio Button is a two-states button that can be either checked or unchecked and it’s the same
as CheckBox control, except that it will allow only one option to select from the group of options.
● The user can press or click on the radio button to make it select. In android, CheckBox control
allow users to change the state of control either Checked or Unchecked but the radio button
cannot be unchecked once it is checked.
● Generally, we can use RadioButton controls in an android application to allow users to select
only one option from the set of values.
● Following is the pictorial representation of using RadioButton control in android applications.
In android, we use radio buttons with in a RadioGroup to combine multiple radio buttons into
one group and it will make sure that users can select only one option from the group of multiple
options.
By default, the android RadioButton will be in OFF (Unchecked) state. We can change the
default state of RadioButton by using android:checked attribute.
In case, if we want to change the state of RadioButton to ON (Checked), then we need to set
android:checked = “true” in our XML layout file.
In android, we can create RadioButton control in two ways either in the XML layout file or create it in the Activity
file programmatically.
Create RadioButton in XML Layout File
Following is the sample way to define RadioButton control using RadioGroup in the XML layout file in the
android application.
In android, we can create RadioButton control programmatically in activity file based on our
requirements.
Following is the example of creating a RadioButton control dynamically in activity file.
This is how we can define RadioButton in XML layout file or programmatically in activity file based
on our requirements.
Handle Android RadioButton Click Events
Generally, whenever the user click on RadioButton to Select or Deselect the RadioButton object will
receives an on-click event.
In android, we can define RadioButton click event in two ways either in the XML layout file or create it in
Activity file programmatically.
We can define click event handler for button by adding the android:onClick attribute to the
<RadioButton> element in our XML layout file.
The value of android:onClick attribute must be the name of the method which we need to call in
response to a click event and the Activity file which hosting XML layout must implement the corresponding
method.
Following is the example of defining a RadioButton click event using android:onClick attribute in XML layout file.
To define RadioButton click event programmatically, create View.OnClickListener object and assign it to the
button by calling setOnClickListener(View.OnClickListener) like as shown below.
Once we are done with the creation of layout with required controls, we need to load the XML layout resource
from our activity onCreate() callback method, for that open main activity file MainActivity.java and write the
code like as shown in next…
For Other Component
https://www.tutlane.com/tutorial/android/android-radiobutton-with-examples
https://www.tutlane.com/tutorial/android/android-checkbox-with-examples
https://www.tutlane.com/tutorial/android/android-toggle-button-with-exampl
es
https://www.tutlane.com/tutorial/android/android-spinner-dropdown-list-with
-examples