You are on page 1of 65

UNIT II

Android Programming
Android User Interface :
Understanding the components of a screen : Views and ViewGroups, LinearLayout ,
AbsoluteLayout, TableLayout, RelativeLayout , FrameLayout , ScrollLayout ,ScrollView

Adapting to Display Orientation: Anchoring Views , Resizing and Repositioning


Managing Changes to Screen Orientation: Persisting State Information during Changes in
Configuration , Detecting Orientation Changes, Controlling the Orientation of the Activity

Utilizing Action Bar : Adding Action Items to the Action Bar, Customizing the Action Items and
Application Icon
Views and ViewGroups

● Android Layout is used to describe the user interface for an app or activity,
● it stores the UI elements that will be visible to the user.
● An android app’s user interface is made up of a series of View and ViewGroup
elements.
● The android apps will contain one or more activities and each activity is one screen
of the app.
● In Android apps, the two very central classes are the Android View class and
ViewGroup class.
● View or ViewGroup subclasses are used to build the GUI elements.
Views and ViewGroups

● View is a basic building block of UI (User Interface) in android.


● A view is a small rectangular box that responds to user inputs. Eg: EditText, Button,
CheckBox, etc.
● View objects are usually called “widgets”

● ViewGroup is an invisible container of other views (child views) and other


ViewGroup.
● Eg: LinearLayout is a ViewGroup that can contain other views in it.
● ViewGroup objects are generally called “layouts”

● As the name states View is singular and the group of Views is the ViewGroup.
Views and ViewGroups

View

● The View class is the base class or we can say that it is the superclass for all the
GUI components in android.
● EditText class is used to accept the input from users in android apps, which is a
subclass of View,
● TextView class which is used to display text labels in Android apps is also a
subclass of View.
● View refer to the android.view.View class, which is the base class of all UI classes.
android.view.View class is the root of the UI class hierarchy.
● So from an object point of view, all UI objects are View objects.
Views and ViewGroups

● Following are some of the common View subclasses that will be used in android
applications.
1. TextView
2. EditText
3. ImageView
4. RadioButton
5. Button
6. ImageButton
7. CheckBox
8. DatePicker
9. Spinner
10. ProgressBar and etc.

These are some of the view subclass available in android.


Views and ViewGroups

ViewGroup

● The ViewGroup class is a subclass of the View class.


● it will act as a base class for layouts and layouts parameters.
● The ViewGroup will provide an invisible container to hold other Views or
ViewGroups and to define the layout properties.
● For example, Linear Layout is the ViewGroup that contains UI controls like Button,
TextView, etc., and other layouts also.
Views and ViewGroups

● ViewGroup Refer to the android.view.ViewGroup class, which is the base class of


some special UI classes that can contain other View objects as children.
● Since ViewGroup objects are also View objects, multiple ViewGroup objects and
View objects can be organized into an object tree to build a complex UI structure.
Views and ViewGroups

Following are the commonly used ViewGroup subclasses used in android applications.

1. FrameLayout
2. WebView
3. ListView
4. GridView
5. LinearLayout
6. RelativeLayout
7. TableLayout and many more.
Views and ViewGroups

● Attributes
● Every View and ViewGroup object supports certain XML attributes
● Three categories

1. Specific to a View object

Example: TextView supports the textSize attribute

2. Common to all View objects

They are inherited from the root View class

Example: id attribute

3. Layout parameters

Attributes that describe certain layout orientations of the View object

Defined by that object's parent ViewGroup object.


Views and ViewGroups

● ID Attribute
• View objects have an integer ID associated with it, to uniquely
identify the View within the layout tree structure
• Example:
● android:id="@+id/btnOK"
@ indicates XML parser should parse this string
+ indicates that it’s a new resource name that must be created
Views and ViewGroups

Layout Parameters

● Those attributes for the View that are appropriate for the ViewGroup in which it
resides
○ Example: layout_width, layout_height
● Width and height can be specified with exact measurements or by specifying
○ wrap_content: view to size itself to the dimensions required by its content
○ match_parent: view to become as big as its parent view group will allow
Views and ViewGroups

Layout Positions

● The geometry of a view is that of a rectangle


● A view has a location, expressed as a pair of left and top coordinates, and two
dimensions expressed as a width and height

Views and ViewGroups

● To retrieve the location of a view

getLeft() and getTop()

● Other methods

getRight() and getBottom()

● To get the dimensions

getWidth() and getHeight()


Views and ViewGroups

Padding and Margin

● the margin property controls the space outside an element,


● the padding property controls the space inside an element.
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
● If you apply android:orientation=”horizontal” then elements will be arranged one
after another in a horizontal manner.
Linear Layout
Linear Layout
Linear Layout

Attributes Description

It is defined individually to the child’s views to specify how LinearLayout


android:layout_weight
divides the remaining space amongst the views it contains

android:orientation How the elements should be arranged in the layout. It can be horizontal or vertical.

It specifies how an object should position its content on its X and Y axes.
android:gravity
Possible values are – center_vertical, fill, center, bottom, end, etc.

android:id This gives a unique id to the layout.


Linear Layout
Linear Layout
Linear Layout
Absolute Layout

● An Absolute Layout allows you to specify the exact location .i.e., X and Y
coordinates of its children with respect to the origin at the top left corner of the
layout.
● The absolute layout is less flexible and harder to maintain for varying sizes of
screens that’s why it is not recommended.
● Although Absolute Layout is deprecated now.
Absolute Layout
Absolute Layout

● Some of the important Absolute Layout attributes are the following:


● android:id: It uniquely specifies the absolute layout
● android:layout_x: It specifies X-Coordinate of the Views (Possible values of this is
in density-pixel or pixel)
● android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this is
in dp or px)

Absolute Layout
View
Views and ViewGroups ViewGroup

View is a simple rectangle box that responds to the ViewGroup is the invisible container. It holds View and
user’s actions. ViewGroup

View is the SuperClass of All component like TextView, ViewGroup is a collection of Views(TextView, EditText,
EditText, ListView, etc ListView, etc..), somewhat like a container.

A View object is a component of the user interface (UI) A ViewGroup object is a layout, that is, a container of other
like a button or a text box, and it’s also called a widget. ViewGroup objects (layouts) and View objects (widgets)

For example, LinearLayout is the ViewGroup that contains


Examples are EditText, Button, CheckBox, etc.
Button(View), and other Layouts also.

View refers to the android.view.View class ViewGroup refers to the android.view.ViewGroup class

android.view.View which is the base class of all UI


ViewGroup is the base class for Layouts.
classes.
FrameLayout

● 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.
FrameLayout
FrameLayout
Table Layout

● Android TableLayout is a ViewGroup subclass which is used to display the child


View elements in rows and columns.
● It will arrange all the children elements into rows and columns and does not
display any border lines in between rows, columns or cells.
● The working of TableLayout is almost similar to HTML table and it contains as
many columns as row with the most cells.
Table Layout
RelativeLayout

● The relative layout is used to arrange the child views in a proper order which
means arranging the child objects relative to each other.
● To arrange them in a proper order we need to use the relative layout.
● To arrange them we need some advanced properties.
● There are so many properties that are supported by relative layout. some of the
most used properties are listed below
RelativeLayout

XML attributes Description

layout_alignParentLeft It is set “true” to match the left edge of view to the left edge of parent.

layout_alignParentRight It is set “true” to match the right edge of view to the right edge of parent.

layout_alignParentTop It is set “true” to match the top edge of view to the top edge of parent.

layout_alignParentBottom It is set “true” to match the bottom edge of view to the bottom edge of parent.

layout_alignLeft It accepts another sibling view id and align the view to the left of the specified view id

It accepts another sibling view id and align the view to the right of the specified view
layout_alignRight
id.

layout_alignStart It accepts another sibling view id and align the view to start of the specified view id.
layout_alignEnd It accepts another sibling view id and align the view to end of specified view id.

layout_centerInParent When it is set “true”, the view will be aligned to the center of parent.

layout_centerHorizontal When it is set “true”, the view will be horizontally centre aligned within its parent.

layout_centerVertical When it is set “true”, the view will be vertically centre aligned within its parent.

layout_toLeftOf It accepts another sibling view id and places the view left of the specified view id.

layout_toRightOf It accepts another sibling view id and places the view right of the specified view id.

layout_toStartOf It accepts another sibling view id and places the view to start of the specified view id.

layout_toEndOf It accepts another sibling view id and places the view to end of the specified view id.

layout_above It accepts another sibling view id and places the view above the specified view id.

layout_below It accepts another sibling view id and places the view below the specified view id.
RelativeLayout
RelativeLayout
RelativeLayout
RelativeLayout
RelativeLayout
RelativeLayout
RelativeLayout
RelativeLayout
ScrollView

● In Android, a ScrollView is a view group that is used to make vertically scrollable


views.
● A scroll view contains a single direct child only. In order to place multiple views in
the scroll view, one needs to make a view group(like LinearLayout) as a direct child
and then we can define many views inside it.
● A ScrollView supports Vertical scrolling only, so in order to create a horizontally
scrollable view, HorizontalScrollView is used.

Attribute Description

Defines whether the scrollview should stretch its content to fill the
android:fillViewport
viewport.
Handling Display Orientation Changes

● Android devices come in various shapes and sizes, and users frequently switch
between portrait and landscape orientations.
● To ensure our applications look great in any scenario, we need to handle display
orientation changes.
● .In Android, we accomplish this by overriding the onConfigurationChanged
method.
● This method allows us to dynamically adapt our UI based on the current device
orientation.
@Override

public void onConfigurationChanged(Configuration newConfig) {

super.onConfigurationChanged(newConfig);

if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

// Handle landscape orientation

} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

// Handle portrait orientation

}
Anchoring Views with ConstraintLayout

● Creating responsive layouts is a fundamental aspect of Android development.


● ConstraintLayout provides a powerful way to anchor views, ensuring they maintain
a consistent position relative to their parent or other views.
● The example code snippet demonstrates how to anchor a view using
ConstraintLayout in XML.
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
Resizing Views Dynamically

● To adapt to different screen sizes, we often need to resize views dynamically.


● The following code snippet illustrates how to change the width of a view
programmatically.

Button myButton = findViewById(R.id.myButton);

ViewGroup.LayoutParams params = myButton.getLayoutParams();

params.width = newWidthInPixels;

myButton.setLayoutParams(params);
Repositioning Views Dynamically

● In certain scenarios, we may need to reposition views dynamically.


● This code snippet demonstrates how to change the position of a view within its
parent.

Button myButton = findViewById(R.id.myButton);

ViewGroup.LayoutParams params = myButton.getLayoutParams();

params.leftMargin = newLeftMarginInPixels;

params.topMargin = newTopMarginInPixels;

myButton.setLayoutParams(params);
Challenges in Screen Orientation Changes

● A user is deeply engaged in your app, and suddenly they rotate their device.
● The challenge here is maintaining the continuity of their experience without any
data loss or disruptions.
● Our goal is to overcome these challenges and create a smooth transition during
screen orientation changes.
Persisting State Information during Changes

● To address these challenges, Android provides us with the onSaveInstanceState


and onRestoreInstanceState methods.
● These allow us to save critical data before a configuration change and restore it
afterward.
● This ensures users don't lose their place in the app when, for example, switching
from portrait to landscape mode.
@Override

protected void onSaveInstanceState(Bundle outState) {

super.onSaveInstanceState(outState);

outState.putString("key", "value"); // Save your data here

@Override

protected void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);

String value = savedInstanceState.getString("key"); // Retrieve your data here

}
Controlling the Orientation of the Activity

● Controlling the orientation of our activities can be critical in certain situations.


● We can set the desired orientation either in the AndroidManifest.xml file or
dynamically in our code.
<activity
android:name=".YourActivity"
android:screenOrientation="portrait">
<!-- or "landscape" for landscape orientation -->
</activity>

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
The Significance of Action Items

● Let's start by understanding the significance of action items.


● In the realm of Android app development, action items are like shortcuts to
essential functions, providing users with quick access to frequently used features.
● A well-designed set of action items can significantly improve user experience and
navigation within an app.
Adding Action Items to the Action Bar

● The Action Bar is that strip at the top of our app that typically holds our app's title
and a few icons for various actions.

Components included in the ActionBar are:

1. App Icon: Display the branding logo/icon of the application.


2. View Controls: Section that displays the name of the application or current activity.
Developers can also include spinner or tabbed navigation for switching between
views.
3. Action Button: Contains some important actions/elements of the app that may be
required to the users frequently.
4. Action Overflow: Include other actions that will be displayed as a menu.
Default ActionBar

● As mentioned earlier, every android app contains an ActionBar by default.


● This pre-included ActionBar display title for the current activity that is managed by
the AndroidManifest.xml file.
● The string value of the application’s title is provided by @string/app_name
resource present under the application nodes.

<application

android:label=”@string/app_name”

</application>
Creating a new directory and design items of ActionBar

● To code the elements of ActionBar, create a new directory in the resource folder of
the application project files.
● Right-click on the res folder and selects New -> Directory. Give the name “menu” to
the new directory.
● create a new Menu Resource File by right click on the menu directory.
● a new file named “main.xml” must be created under the menu directory.
● In this file, one can declare the items which will be displayed as the action buttons
of the ActionBar.
● Every menu items, the following attributes are needed to be configured:
● android:title: Its value contains the title of the menu item that will be displayed when a
user clicks and holds that item in the app.
● android:id: A unique ID for the menu item that will be used to access it anywhere in the
whole application files.
● android:orderInCategory: The value of this attribute specify the item’s position in the
ActionBar.
○ provide the same value of this attribute for all items and the position will be defined
in the same order as they are declared in the code.
● app:showAsAction: This attribute defines how the item is going to be present in the
action bar. There are four possible flags to choose from:
○ a. always:
○ b. ifRoom:
○ c. never:
○ d. withText:
● android:icon: The icon of an item is referenced in the drawable directories through this
attribute.
Icon of an ActionBar Item

● In order to provide an icon to an item, right-click on the res folder, select new, and
then Image Asset. A dialog box will appear, choose the Icon Type as Action Bar and
Tab Icons.
● Choose assets type as “Clip Art” and select an image from the clip art collection.
Provide a desired name to the icon.
● Click on Next, then Finish.
● This icon will now get loaded in the drawable directory of the res folder.
● The name provided by the developers to these icons will now be used to reference
the item’s icon resource.
Color of the ActionBar

● located in the values directory of the res folder.


● To change the default color of the ActionBar, one has to change the colorPrimary
resource.

Handling Action Item Clicks

This is done in the onOptionsItemSelected method. Here's a code snippet:

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.action_item:

return true;

default:

return super.onOptionsItemSelected(item);

}
Adding Action Items to the Action Bar

To add action items, we override the onCreateOptionsMenu method. Here's a simple


code snippet:

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.your_menu, menu);

return true;

}
Application Icon

● Our application icon is a crucial part of our app's identity and branding.
● It's often the first thing users notice about our app. So, let's see how we can
customize the application icon.
● Customizing the application icon is quite straightforward.
● In the AndroidManifest.xml file, within the <application> element, we can use the
android:icon attribute to set our app's launcher icon and the android:logo attribute
to set a different icon for the Action Bar:

You might also like