0% found this document useful (0 votes)
4 views38 pages

Android Assignment Answers

The document provides an overview of Android, detailing its components, architecture, and application lifecycle. It explains key concepts such as Activities, Views, Intents, Services, and Content Providers, along with a practical example of creating a 'Hello World' Android app. Additionally, it covers the Android Activity Lifecycle and various View types, including TextView, EditText, and Button, along with their properties.

Uploaded by

Ganesh Jadhav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views38 pages

Android Assignment Answers

The document provides an overview of Android, detailing its components, architecture, and application lifecycle. It explains key concepts such as Activities, Views, Intents, Services, and Content Providers, along with a practical example of creating a 'Hello World' Android app. Additionally, it covers the Android Activity Lifecycle and various View types, including TextView, EditText, and Button, along with their properties.

Uploaded by

Ganesh Jadhav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name :- Ganesh K Jadhav.

Course :- Android Developer


Government Polytechnic , Pune.
Faculty :- Mr. Bapusaheb Shinde.
Date :- January 18, 2019.

1
1) What is Android Which are Android Components Explain with Arctitecture diagram.

Answer :-

1.1 What is Android?

Android is a mobile operating system that is based on a modified version of Linux.


It is operating system for mobile devices such as tablet computers and smartphones. Android is open
source and free. Android code was released under the open-source Apache License, which means that
anyone who wants to use Android can do so by downloading the full Android source code.
Java language is mainly used to write the android code even though other languages can be used. The
goal of android is to create a successful real-world product that improves the mobile experience for end
users.

1.2 Which are Android Components ?

An android component is simply a piece of code that has a well defined life cycle.
The fundamental components of android are activities, views, intents, services, content providers,
fragments and [Link].

a. Activity - An activity is a class that represents a single screen. It is like a Frame in AWT.

b. View - A view is the UI element such as button, label, text field etc. Anything that we see is a view.

c. Intents - An Intent is a simple message object that is used to communicate between android
components such as activities, content providers, broadcast receivers and services.
Uses of Intents -
To Transfer data between activities.
To start a new activity using startActivity().
To Start the service.
To Display a web page.
To Display a list of contacts.
To Broadcast a message.
To Dial a phone call.

e.g. following code to view a webpage

Intent intent=new Intent(Intent.ACTION_VIEW);


[Link]([Link]("[Link]
startActivity(intent);

d. Service - Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application
whereas remote service is accessed remotely from other applications running on the same device.

e. Content Provider - Content Providers are used to share data between the applications.

2
f. Fragments - Fragments are like parts of activity. An activity can display one or more fragments on the
screen at the same time.

g. [Link] - It contains information about activities, content providers, permissions etc.

Android architecture

Figure 1.1 - Architecture of Android

Linux kernel - This is the kernel on which Android is based. This layer contains all the low level device
drivers for the various hardware components of an Android device. Core services (including hardware
drivers, process and memory management,
security, network, and power management) are handled by a Linux kernel. The kernel
also provides an abstraction layer between the hardware and the remaining software components.

Native Libraries - These contain all the code that provides the main features of an Android OS. For
example, the SQLite library provides database support. The WebKit library provides functionalities for
web browsing. FreeType provides font support, Media library is used for playing and recording audio
and video formats.

Android Runtime -
Core Libraries - At the same layer as the libraries, the Android runtime provides a set of core libraries
that enable developers to write Android apps using the Java programming language.

3
DVM - The Android runtime also includes the Dalvik Virtual Machine (DVM), which enables every
Android application to run in its own process, with its own instance of the Dalvik virtual machine
(Android applications are compiled into the Dalvik executables). Dalvik is a specialized virtual machine
designed specifically for Android and optimized for battery-powered mobile devices with limited
memory and CPU. DVM consumes less memory and provides fast performance.

Application Framework -The application framework also called as Android Framework provides the
classes and interfaces used to create Android applications.

Applications - At this top layer, we find applications that ship with the Android device
(such as Phone, Contacts, Browser, etc.), as well as applications user downloads and installs
from the Android Market. Any applications that android develover writes are located at this layer.
These applications are using android framework or application framework that uses android runtime
and libraries. Android runtime and native libraries are using linux kernal.

4
2) Explain Hello World Android App with code

Answer :-
Install android studio with SDK tools. Create new project. Change Application name and project
location. Select 'Include C++ support ' only if we want to write some code in C++.
Select Phone and Tablet. Select API 15 which can target Android 4.0.3 ( IceCreamSandwich ) i.e. app can
run on 97.1% devices that are active on the Google Play Store. See Screenshot 2.1

Screenshot 2.1 - Select API 15

Select Empty Activity. Enter Activity Name as 'MainActivity'. Check 'Generate Layout File' And Enter
Layout Name as 'activity_main'. Layout means UI. i.e. Presentation [Link] Backwards Compatability
(AppCompact) . If this is false , this activity base class will be Activity insted of AppCompactActivity. See
Screenshot 2.2

5
Screenshot 2.2 - Check 'Generate Layout File' And Check 'Backwards Compatability (AppCompact)'.

Click Finish.

activity_main.xml contains following code

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

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link]

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"

6
tools:context="[Link]">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

</RelativeLayout>

The source code for MainActivity class is as below.

package [Link];

import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}

Build apk and copy to phone. Then install it and run.

7
Output :-

Screenshot 2.1 - Program displaying text 'Hello World!'.

8
3) Android Activity Lifecycle with diagram

Answer :-

Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on
the top of the stack and becomes the running activity -- the previous activity always remains below it in
the stack, and will not come to the foreground again until the new activity exits.

An activity has essentially four states:

If an activity is in the foreground of the screen (at the top of the stack), it is active or running.

If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has
focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and
member information and remains attached to the window manager), but can be killed by the system in
extreme low memory situations.

If an activity is completely obscured by another activity, it is stopped. It still retains all state and member
information, however, it is no longer visible to the user so its window is hidden and it will often be killed
by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop the activity from memory by either asking it to
finish, or simply killing its process. When it is displayed again to the user, it must be completely
restarted and restored to its previous state.

The following diagram shows the important state paths of an Activity. The square rectangles represent
callback methods you can implement to perform operations when the Activity moves between states.
The colored ovals are major states the Activity can be in.

9
Figure 3.1 - Activity Lifecycle

The entire lifecycle of an activity is defined by the following Activity methods. All of these can be
overridento do appropriate work when the activity changes state. All activities will implement
onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to
data and otherwise prepare to stop interacting with the user. We should always call up to our superclass
when implementing these methods.

10
public class Activity extends ApplicationContext {
protected void onCreate(Bundle savedInstanceState);

protected void onStart();

protected void onRestart();

protected void onResume();

protected void onPause();

protected void onStop();

protected void onDestroy();


}

In general the movement through an activity's lifecycle looks like this:

Method Description Killable Next


onCreate() Called when the activity No onStart()
is first created. This is
where you should do all
of your normal static
set up: create views,
bind data to lists, etc.
This method also
provides you with a
Bundle containing the
activity's previously
frozen state, if there
was one.
Always followed
by onStart().

onRestart() Called after your No onStart()


activity has been
stopped, prior to it
being started again.
Always followed
by onStart()

11
onStart() Called when the activity No onResume()or
is becoming visible to onStop()
the user.
Followed
by onResume() if the
activity comes to the
foreground,
or onStop() if it
becomes hidden.

onResume() Called when the activity No onPause()


will start interacting
with the user. At this
point your activity is at
the top of the activity
stack, with user input
going to it.
Always followed
by onPause().

onPause() Called when the system Yes only for pre- onResume()or
is about to start Honeycomb onStop()
resuming a previous
activity. This is typically
used to commit
unsaved changes to
persistent data, stop
animations and other
things that may be
consuming CPU, etc.
Implementations of this
method must be very
quick because the next
activity will not be
resumed until this
method returns.
Followed by
either onResume()if the
activity returns back to
the front, or onStop() if
it becomes invisible to
the user.

onStop() Called when the activity Yes onRestart()or


is no longer visible to onDestroy()
the user, because
another activity has
been resumed and is

12
covering this one. This
may happen either
because a new activity
is being started, an
existing one is being
brought in front of this
one, or this one is being
destroyed.
Followed by
either onRestart() if this
activity is coming back
to interact with the
user, or onDestroy() if
this activity is going
away.

onDestroy() The final call you Yes nothing


receive before your
activity is destroyed.
This can happen either
because the activity is
finishing (someone
called finish() on it), or
because the system is
temporarily destroying
this instance of the
activity to save space.
You can distinguish
between these two
scenarios with the
isFinishing() method.

Note - for those methods that are marked as being killable, after that method returns the process
hosting the activity may be killed by the system.

onPause() is marked as killable pre-Honeycomb, and onStop() is marked as killable for all API levels. So
this means that pre-Honeycomb, your app is killable after onPause(), and on Honeycomb+ your app is
killable after onStop().

Starting with Honeycomb, an application is not in the killable state until its onStop() has returned.

13
4) What is mean by View Explain in brief : TextView,EditText,Spinner,Button,ListView,LinearLayout
with properties with diagrams

View - View is an useful class provided by Android API.

This class represents the basic building block for user interface components. A View occupies a
rectangular area on the screen and is responsible for drawing and event handling.

A View is an object that draws something on the screen that the user can interact with.

View is the base class for widgets, which are used to create interactive UI components (buttons, text
fields, etc.).

The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other
Views (or other ViewGroups) and define their layout properties. ViewGroup's object holds other View
(and ViewGroup) objects in order to define the layout of the user interface.

We define our layout in an XML file which offers a human-readable structure for the layout, similar to
HTML.

Using Views

All of the views in a window are arranged in a single tree. You can add views either from code or by
specifying a tree of views in one or more XML layout files. There are many specialized subclasses of
views that act as controls or are capable of displaying text, images, or other content.

Once you have created a tree of views, there are typically a few types of common operations you may
wish to perform:

Set properties: for example setting the text of a TextView. The available properties and the methods
that set them will vary among the different subclasses of views. Note that properties that are known at
build time can be set in the XML layout files.

Set focus: The framework will handle moving focus in response to user input. To force focus to a specific
view, call requestFocus().

Set up listeners: Views allow clients to set listeners that will be notified when something interesting
happens to the view. For example, all views will let you set a listener to be notified when the view gains
or loses focus. You can register such a listener using
setOnFocusChangeListener([Link]). Other view subclasses offer
more specialized listeners. For example, a Button exposes a listener to notify clients when the button is
clicked.

14
Set visibility: You can hide or show views using setVisibility(int).

4.1 TextView - A user interface element that displays text to the user.

Some of the properties of TextView are as below

android:id - This is the ID which uniquely identifies the control.

android:capitalize - If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types.

Don't automatically capitalize anything - 0

Capitalize the first word of each sentence - 1

Capitalize the first letter of every word - 2

Capitalize every character - 3

android:cursorVisible - Makes the cursor visible (the default) or invisible. Default is false.

android:editable - If set to true, specifies that this TextView has an input method.

android:fontFamily - Font family (named by string) for the text.

android:gravity - Specifies how to align the text by the view's x- and/or y-axis when the text is smaller
than the view.

android:hint - Hint text to display when the text is empty.

android:inputType - The type of data being placed in a text field. Phone, Date, Time, Number, Password
etc.

android:maxHeight - Makes the TextView be at most this many pixels tall.

android:maxWidth - Makes the TextView be at most this many pixels wide.

android:minHeight - Makes the TextView be at least this many pixels tall.

android:minWidth - Makes the TextView be at least this many pixels wide.

android:password - Whether the characters of the field are displayed as password dots instead of
themselves. Possible value either "true" or "false".

android:phoneNumber - If set, specifies that this TextView has a phone number input method. Possible
value either "true" or "false".

15
android:text - Text to display.

android:textAllCaps - Present the text in ALL CAPS. Possible value either "true" or "false".

android:textColor - Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or
"#aarrggbb".

android:textColorHighlight - Color of the text selection highlight.

android:textColorHint - Color of the hint text. May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".

android:textIsSelectable - Indicates that the content of a non-editable text can be selected. Possible
value either "true" or "false".

android:textSize - Size of the text. Recommended dimension type for text is "sp" for scaled-pixels
(example: 15sp).

android:textStyle - Style (bold, italic, bolditalic) for the text. You can use or more of the following values
separated by '|'.
normal - 0
bold - 1
italic - 2

android:typeface - Typeface (normal, sans, serif, monospace) for the text. You can use or more of the
following values separated by '|'.
normal - 0
sans - 1
serif - 2
monospace - 3

Example :- XML snippet showing use of TextView to display text.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

Output :-

16
Screenshot 4.1 - TextView displaying text 'Hello World!'.

4.2 EditText

It is the subclass of TextView that includes rich text editing capabilities.

EditText attributes :-

android:autoText - If set, specifies that this TextView has a textual input method and automatically
corrects some common spelling errors.

android:drawableBottom - This is the drawable to be drawn below the text.

android:drawableRight - This is the drawable to be drawn to the right of the text.

android:editable - If set, specifies that this TextView has an input method.

android:text - This is the Text to display.

Above properties are inherited from [Link] Class.

android:background - This is a drawable to use as the background.

android:contentDescription - This defines text that briefly describes content of the view.

17
android:id - This supplies an identifier name for this view.

android:onClick - This is the name of the method in this View's context to invoke when the view is
clicked.

android:visibility - This controls the initial visibility of the view.

Above properties are inherited from [Link] Class

Screenshot 4.2 - EditText in different modes.

4.3 Spinner

A dropdown component is called a spinner on the Android platform. A spinner provides a drop-down
list of values. It allows user to choose a single value from a set of values. When user touch it, it expands
to show the list so that user can pick a single value. It has two operating modes. There is a dropdown
mode where the options appear below the menu (or above if there’s no room below), and there is pop-
up mode where the options appear in a pop-up window for the users to select from.

android:dropDownHorizontalOffset
Amount of pixels by which the drop down should be offset horizontally.

android:dropDownSelector
List selector to use for spinnerMode="dropdown" display.

android:dropDownVerticalOffset
Amount of pixels by which the drop down should be offset vertically.

android:dropDownWidth
Width of the dropdown in spinnerMode="dropdown".

18
android:gravity
Gravity setting for positioning the currently selected item.
Must be one or more (separated by '|') of the following constant values.
bottom -50
center- 11
center_horizontal - 1
center_vertical - 10
left - 3
right - 5
start - 800003
top - 30

android:popupBackground
Background drawable to use for the dropdown in spinnerMode="dropdown".

android:prompt
The prompt to display when the spinner's dialog is shown.

android:spinnerMode
Display mode for spinner options.
Must be one of the following constant values.
dialog - 0
dropdown - 1

android:textAlignment
Defines the alignment of the text.

android:textDirection
Defines the direction of the text.

android:scrollbars
Defines which scrollbars should be displayed on scrolling or not.

android:onClick
Name of the method in spinners context to invoke when the spinner is clicked.

android:layoutDirection
Defines the direction of layout drawing.

android:longClickable
Defines whether spinner reacts to long click events.

android:foreground
Defines the drawable to draw over the content.

android:background

19
A drawable to use as the background.

android:entries
Reference to an array resource that will populate the Spinner.

Screenshot 4.3 - The Google Maps app uses the dropdown spinner navigation as part of the Action Bar.

4.4 Button

A Button is an user interface element which can be tapped , pressed, or clicked, by the user to perform
an action.

android:autoText - If set, specifies that this TextView has a textual input method and automatically
corrects some common spelling errors.

android:drawableBottom - This is the drawable to be drawn below the text.

android:drawableRight - This is the drawable to be drawn to the right of the text.

android:editable - If set, specifies that this TextView has an input method.

android:text - This is the Text to display.

Above properties are inherited from [Link] Class.

20
android:background - This is a drawable to use as the background.

android:contentDescription - This defines text that briefly describes content of the view.

android:id - This supplies an identifier name for this view.

android:onClick - This is the name of the method in this View's context to invoke when the view is
clicked.

android:visibility - This controls the initial visibility of the view.

Above properties are inherited from [Link] Class

Screenshot 4.4 - Program displays a message when user clicked a Button.

4.5 ListView

Android ListView is a view which groups several items and display them in vertical scrollable list. It is
vertically-scrollable collection of views, where each view is positioned immediatelybelow the previous
view in the list. The list items are automatically inserted to the list using an Adapter that pulls content
from a source such as an array or database.

21
An adapter actually bridges between UI components and the data source that fill data into UI
Component. Adapter holds the data and send the data to adapter view, the view can takes the data
from adapter view and shows the data on different views like as spinner, list view, grid view etc.

The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to
an Adapter, which retrieves data from an external source and creates a View that represents each data
entry.

Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and
building views for an AdapterView ( i.e. ListView or GridView). The common adapters are
ArrayAdapter,Base Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and
WrapperListAdapter.

android:id
This is the ID which uniquely identifies the layout.

android:divider
This is drawable or color to draw between list items.

android:dividerHeight
This specifies height of the divider. This could be in px, dp, sp, in, or mm.

android:entries
Specifies the reference to an array resource that will populate the ListView.

android:footerDividersEnabled
When set to false, the ListView will not draw the divider before each footer view. The default value is
true.

android:headerDividersEnabled
When set to false, the ListView will not draw the divider after each header view. The default value is
true.

22
Screenshot 4.5 - Simple ListView showing months of year.

4.6 LinearLayout

LinearLayout is a view group that aligns all children in a single direction, vertically in a single row or
horizontally in a single column. We can specify the layout direction with the android:orientation
attribute. Android:orientation is set to specify whether child views are displayed in a row or column.
All children of a LinearLayout are stacked one after the other, so a vertical list will only have one child
per row, no matter how wide they are, and a horizontal list will only be one row high (the height of the
tallest child, plus padding).
To control how linear layout aligns all the views it contains, set a value for android:gravity.

Layout Weight
LinearLayout also supports assigning a weight to individual children with the android:layout_weight
attribute. This attribute assigns an "importance" value to a view in terms of how much space it should
occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent
view. Child views can specify a weight value, and then any remaining space in the view group is assigned
to children in the proportion of their declared weight. Default weight is zero.

android:layout_gravity - Gravity specifies how a component should be placed in its group of cells.

23
android:layout_weight - Indicates how much of the extra space in the LinearLayout is allocated to the
view associated with these LayoutParams.

android:layout_height - Specifies the basic height of the view.

android:layout_width - Specifies the basic width of the view.

android:layout_margin - Specifies extra space on the left, top, right and bottom sides of this view.
android:layout_marginBottom - Specifies extra space on the bottom side of this view.
android:layout_marginEnd - Specifies extra space on the end side of this view.
android:layout_marginHorizontal - Specifies extra space on the left and right sides of this view.
android:layout_marginLeft - Specifies extra space on the left side of this view.
android:layout_marginRight - Specifies extra space on the right side of this view.
android:layout_marginStart - Specifies extra space on the start side of this view.
android:layout_marginTop - Specifies extra space on the top side of this view.
android:layout_marginVertical - Specifies extra space on the top and bottom sides of this view.

Important XML attributes

android:id
This is the ID which uniquely identifies the layout.

android:baselineAligned
When set to false, prevents the layout from aligning its children's baselines. This attribute is particularly
useful when the children use different values for gravity. The default value is true. May be a boolean
value, such as "true" or "false".

android:baselineAlignedChildIndex
When a linear layout is part of another layout that is baseline aligned, it can specify which of its children
to baseline align to (that is, which child TextView). May be an integer value, such as "100".

android:divider
This is drawable to use as a vertical divider between buttons. You use a color value, in the form of
"#rgb", "#argb", "#rrggbb", or "#aarrggbb".

android:gravity
This specifies how an object should position its content, on both the X and Y axes. Possible values are
top, bottom, left, right, center, center_vertical, center_horizontal etc.
Must be one or more (separated by '|') of the following constant values.

Constant Value Description


bottom 50 Push object to the bottom of its container, not
changing its size.
center 11 Place the object in the center of its container in both
the vertical and horizontal axis, not changing its
size.
center_horizontal 1 Place object in the horizontal center of its container,
not changing its size.

24
center_vertical 10 Place object in the vertical center of its container,
not changing its size.
clip_horizontal 8 Additional option that can be set to have the left
and/or right edges of the child clipped to its
container's bounds. The clip will be based on the
horizontal gravity: a left gravity will clip the right
edge, a right gravity will clip the left edge, and
neither will clip both edges.

clip_vertical 80 Additional option that can be set to have the top


and/or bottom edges of the child clipped to its
container's bounds. The clip will be based on the
vertical gravity: a top gravity will clip the bottom
edge, a bottom gravity will clip the top edge, and
neither will clip both edges.
end 800005 Push object to the end of its container, not changing
its size.
fill 77 Grow the horizontal and vertical size of the object if
needed so it completely fills its container.
fill_horizontal 7 Grow the horizontal size of the object if needed so it
completely fills its container.
fill_vertical 70 Grow the vertical size of the object if needed so it
completely fills its container.
left 3 Push object to the left of its container, not changing
its size.
right 5 Push object to the right of its container, not
changing its size.
start 800003 Push object to the beginning of its container, not
changing its size.
top 30 Push object to the top of its container, not changing
its size.

android:orientation
This specifies the direction of arrangement Or Should the layout be a column or a row? Use
"horizontal" for a row, "vertical" for a column. The default is horizontal.
Must be one of the following constant values.
Constant Value Description
horizontal 0 Defines an horizontal widget.
vertical 1 Defines a vertical widget.

android:weightSum
Defines the maximum weight sum Or Sum up of child weight. If unspecified, the sum is computed by
adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of
the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0. May be a
floating point value, such as "1.2".

android:measureWithLargestChild
When set to true, all children with a weight will be considered having the minimum size of the largest
child. If false, all children are measured normally. May be a boolean value, such as "true" or "false".

25
Equal distribution
To create a linear layout in which each child uses the same amount of space on the screen, set the
android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each
view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1".

Unequal distribution
You can also create linear layouts where the child elements use different amounts of space on the
screen:

If there are three text fields and two of them declare a weight of 1, while the other is given no weight,
the third text field without weight doesn't grow. Instead, this third text field occupies only the area
required by its content. The other two text fields, on the other hand, expand equally to fill the space
remaining after all three fields are measured.

If there are three text fields and two of them declare a weight of 1, while the third field is then given a
weight of 2 (instead of 0), then it's now declared more important than both the others, so it gets half the
total remaining space, while the first two share the rest equally.

Example -

The following code snippet shows how layout weights might work in a "send message" activity. The To
field, Subject line, and Send button each take up only the height they need. This configuration allows the
message itself to take up the rest of the activity's height.

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


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/to" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/subject" />
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/message" />
<Button
android:layout_width="100dp"

26
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@string/send" />
</LinearLayout>

Output :-

27
5) What is Intent and its types. Make app for Navigation between screen with data passing.

Answer :-

An Intent is a simple message object that is used to communicate between android components such as
activities, content providers, broadcast receivers and services.
We can navigate between activities using an intent. Intent is also defined as an abstract description of
an operation to be [Link] are two types of intents
Explicit Intents and Implicit Intents.

Explicit Intents - Suppose if we want to connect one activity to another activity, we can do this quote by
explicit intent. These intents designate the target component by its name.

For example −

// Explicit Intent by specifying its class name


Intent i = new Intent([Link], [Link]);

// Starts TargetActivity
startActivity(i);

We can navigate to second activity (screen) using above intent.

Implicit Intents - These intents do not name a target and the field for the component name is left blank.
Implicit intents are often used to activate components in other applications. For example −

//Method to show a webpage using Implitcit Intent.


public void showWebPage(View view) {
//Instantiate an instance of Intent.
Intent intent = new Intent(Intent.ACTION_VIEW, [Link]("[Link]
//Show target webpage.
startActivity(intent);
}

We can display a webpage using above intent.

App for Navigation between screen with data passing

1. Select blank activity.


2. In activity_main.xml, take a TextView and a Button. The code for activity_main.xml is as below -

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"

28
tools:context="[Link]">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Info to be passed"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pass Info"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="101dp"
android:onClick="Button_Touched"/>

</[Link]>

3. Add another activity to layout. Name this activity as activity_main2.xml. In this activity take a
TextView. The code for this activity is as below -

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link].Main2Activity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
tools:layout_editor_absoluteX="93dp"
tools:layout_editor_absoluteY="224dp" />
</[Link]>

4. In [Link] handle the click event of button. The code for [Link] is as below -

package [Link];

29
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Method handles the click (touch) event of button.


public void Button_Touched (View view)
{
//Find TextView in Java class.
TextView textView1 = (TextView)findViewById([Link].textView1);
//Specify source and target for intent.
Intent intent1 = new Intent ([Link],[Link]);
//Read the text on textview in 'key' by using putExtra method of intent.
[Link]("key", [Link]().toString());
//Start target activity.
startActivity(intent1);
}
}

5. In java class for second activity, read text stored in key and set this text for TextView.
The code for Main2Activity class is as below -

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Main2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main2);
//Find TextView in Java class.

30
TextView textView = (TextView)findViewById([Link]);
// Read text stored in key and set this text for TextView
[Link](getIntent().getExtras().getString("key"));
}
}

6. Build apk and copy to phone. Then install it and run.

Output :-
Screen 1 :-

Screen 2 :-

Screenshot 5.1 - Navigation between screen with data passing.

31
6) Explain Android Simple ListView Example with code.

Answer :-

1. In activity_main.xml take a listview give it an id.

2. In [Link] import folllowing

[Link];
[Link];
[Link];

3. Declare a ListView and an ArrayAdapter of type <String>

4. Populate a String array with data.

5. Find ListView in java using findViewById.

6. Define ArrayAdapter e.g.

ArrayAdapterOfStrings = new ArrayAdapter<>(this, [Link].simple_list_item_1,stringArray);

ArrayAdapterOfStrings is object of ArrayAdapter


stringArray is String array with data.

7. [Link](ArrayAdapterOfStrings);
Pass this object of ArrayAdapter as an argument to setAdapter methiod of ListView.

The code for activity_main.xml is as below -

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link].listview_with_string_array.MainActivity">

<ListView
android:id="@+id/listViewXML"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</[Link]>

The code for [Link] is as below -

32
package [Link].listview_with_string_array;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

ListView listViewJava;
//Populate a string array.
String [] stringArray = {"January", "February",
"March","April","May","June","July","August","September","October","November","December"};

ArrayAdapter <String> ArrayAdapterOfStrings;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
listViewJava=(ListView)findViewById([Link]);
//Instantiate an object of class ArrayAdapter<>.,
// Pass string array and list item as argument to it.
ArrayAdapterOfStrings = new ArrayAdapter<>(this, [Link].simple_list_item_1,stringArray);
[Link](ArrayAdapterOfStrings);
}
}

8. Build apk and copy to phone. Then install it and run.

Output :-

33
Screenshot 6.1 - Simple ListView showing months of year.

34
7) Explain Android Custom ListView Example with code.

Answer :-

[Link] images to be shown in ms-paint and save them as png.


[Link] name should start with small letter and should not start with number.
[Link] images in drawable folder.
[Link] activity_main.xml take a listview and give it an id.
The code for activity_main.xml is as below.

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link].listview_with_image_text.MainActivity">

<ListView
android:id="@+id/listViewInXML"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

</ListView>
</[Link]>

[Link] Click on layout and create new layout resource file name it as list_single.xml, specify layout as
TableLayout.

[Link] TableRow with ImageView and TextView. Give id's to ImageView and TextView.
The code for list_single.xml is as below.

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


<TableLayout xmlns:android="[Link]
android:layout_width="match_parent" android:layout_height="match_parent">
<TableRow>
<ImageView
android:id="@+id/imageViewInXML"
android:layout_height="50dp"
android:layout_width="50dp"/>
<TextView
android:id="@+id/textViewInXML"
android:layout_height="50dp"
android:layout_width="match_parent"
android:paddingLeft="20dp"/>

35
</TableRow>
</TableLayout>

7. Add a new java class to our package, name it as CustomListView. This class extends class
ArrayAdapter<String>.

8. In CustomListView class , declare an object of type activity to hold context, a string array to hold text
to be display and an integer array to hold id's of images.

9. Define a parameterised constructor for CustomListView class with the three declared variables. Inside
constructor , invoke super class constructor using keyword super. Initialise all three variable of this class
with parameters passed to this constructor.

10. Override the getView () method of super class i.e. ArrayAdapter<String> class.
This method returns a view populated with image and text. The source code for [Link]
is as below -

package [Link].listview_with_image_text;

/**
* Created by GANESH on 1/2/2019.
*/
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CustomListView extends ArrayAdapter<String> {

private final Activity context;


private final String[] stringArray;
private final Integer[] intArrayImageId;

//Constructor for class.


public CustomListView (Activity context, String[] stringArray, Integer[] intArrayImageId)
{
super(context, [Link].list_single,stringArray);
[Link] = context;
[Link] = stringArray;
[Link]=intArrayImageId;
}

36
@Override
public View getView (int position, View view , ViewGroup parent)
{
// Inflater to populate view.
LayoutInflater inflater = [Link]();
View rowView = [Link]([Link].list_single,null,true);
TextView textViewInJava = (TextView) [Link]([Link]);
ImageView imageViewInJava = (ImageView) [Link] ([Link]);
//Set text for TextView using strings in Array of Strings.
[Link](stringArray[position]);
//Set images for imageView
[Link](intArrayImageId[position]);
return rowView;
}
}

11. In [Link] , declare a ListView. Populate an array of string with text to be bind to custom
ListView. Populate an integer array with ids (index) of images to be bind.

12. Override onCreate() method. In this method, create an object of CustomListView class. Initialise it
with current activity and these two arrays.

13. Pass this object as an argument to setadapter method of ListView. The source code for
[Link] is as below -

package [Link].listview_with_image_text;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

ListView listViewInJava;

String[] web = {
"Sunil Gavaskar",
"Kapil Dev",
"Sachin Tendulkar",
"Rahul Dravid",
"Saurav Ganguly"

37
};
Integer[] imageId = {
[Link].image1,
[Link].image2,
[Link].image3,
[Link].image4,
[Link].image5
};

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
//Instantiate an object of CustomListView class.
CustomListView adapter = new CustomListView([Link], web, imageId);
listViewInJava = (ListView)findViewById([Link]);
//Pass object of CustomListView class to setAdapter method of ListView.
[Link](adapter);
}
}

14. Build apk and copy to phone. Then install it and run.

Output :-

38

You might also like