0% found this document useful (0 votes)
202 views

UNIT-3 Android User Interface

The document discusses various aspects of Android user interfaces, including: 1. The key components of an Android screen including views, view groups, and common layouts like LinearLayout, RelativeLayout and FrameLayout. 2. Adapting to different display orientations and managing orientation changes. 3. Utilizing the action bar to add action items and customize the application icon.

Uploaded by

Abhay Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
202 views

UNIT-3 Android User Interface

The document discusses various aspects of Android user interfaces, including: 1. The key components of an Android screen including views, view groups, and common layouts like LinearLayout, RelativeLayout and FrameLayout. 2. Adapting to different display orientations and managing orientation changes. 3. Utilizing the action bar to add action items and customize the application icon.

Uploaded by

Abhay Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

UNIT-03

Android User Interface


TOPICS:
3.1. Understanding the components of a screen
• Views and ViewGroups
• LinearLayout
• AbsoluteLayout
• TableLayout
• RelativeLayout
• FrameLayout
• ScrollLayout
• ScrollView
3.2. Adapting to Display Orientation
• Anchoring Views
• Resizing and Repositioning
3.3. Managing Changes to Screen Orientation
• Persisting State Information during Changes in Configuration
• Detecting Orientation Changes
• Controlling the Orientation of the Activity
3.4. Utilizing Action Bar
• Adding Action Items to the Action Bar
• Customizing the Action Items and Application Icon
Understanding the components of A Screen
• An activity displays the user interface of your application, which may contain widgets
like buttons, labels, text boxes, and so on. Typically, you defi ne your UI using an XML fi
le (e.g., the main.xml)
<?xmlversion=”1.0”encoding=”utf-8”?>
<LinearLayoutxmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
</LinearLayout>
Understanding the components of A Screen
• During run time, you load the XML UI in the onCreate() event handler
in your Activity class, using the setContentView() method of the
Activity class:
@Override public voidonCreate(BundlesavedInstanceState)
{ super.onCreate(savedInstanceState); setContentView(R.layout.main); }
• During compilation, each element in the XML fi le is compiled into its
equivalent Android GUI class, with attributes represented by
methods. The Android system then creates the UI of the activity when
it is loaded.
views and viewgroups
• An activity contains Views and ViewGroups.
• A view is a widget that has an appearance on screen.
• Examples of views are buttons, labels, and text boxes. A view derives
from the base class android .view.View.
• One or more views can be grouped together into a ViewGroup. A
ViewGroup (which is itself a special type of view) provides the layout
in which you can order the appearance and sequence of views.
Examples of ViewGroups include LinearLayout and FrameLayout. A
ViewGroup derives from the base class android.view.ViewGroup.
views and viewgroups
• Android supports the following ViewGroups:
• LinearLayout
• AbsoluteLayout
• TableLayout
• RelativeLayout
• FrameLayout
• ScrollView
LinearLayout
• The LinearLayout arranges views in a single column or a single row. Child views can be
arranged either vertically or horizontally. To see how LinearLayout works, consider the
following elements typically contained in the main.xml file:

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


<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
</LinearLayout>
LinearLayout
Attribute Description

layout_width Specifies the width of the View or ViewGroup

layout_height Specifies the height of the View or ViewGroup

layout_marginTop Specifies extra space on the top side of the View or ViewGroup

layout_marginBottom Specifies extra space on the bottom side of the View or ViewGroup

layout_marginLeft Specifies extra space on the left side of the View or ViewGroup

layout_marginRight Specifies extra space on the right side of the View or ViewGroup

layout_gravity Specifi es how child Views are positioned

layout_weight Specifi es how much of the extra space in the layout should be allocated to the View

layout_x Specifi es the x-coordinate of the View or ViewGroup

layout_y Specifi es the y-coordinate of the View or ViewGroup


Units of measurement
• When specifying the size of an element on an Android UI, you should be aware of
the following units of measurement:
• dp — Density-independent pixel. 160dp is equivalent to one inch of physical
screen size. This is the recommended unit of measurement when specifying the
dimension of views in your layout. You can specify either “dp” or “dip” when
referring to a density-independent pixel.
• sp — Scale-independent pixel. This is similar to dpand is recommended for
specifying font sizes.
• pt — Point. A point is defined to be 1/72 of an inch, based on the physical screen
size.
• px — Pixel. Corresponds to actual pixels on the screen. Using this unit is not
recommended, as your UI may not render correctly on devices with different
screen sizes.
AbsoluteLayout
<?xml version=”1.0” encoding=”utf-8”?>
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=http://schemas.android.com/apk/res/android
>
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px”
/>
<Button
android:layout_width=”113dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”12px”
android:layout_y=”361px”
/>
</AbsoluteLayout>
TableLayout
• The TableLayout groups views into rows and columns. You use the element to designate a row in the table. Each row
can contain one or more views. Each view you place within a row forms a cell. The width of each column is determined
by the largest width of each cell in that column.

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


<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”
>
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120px”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200px” />
</TableRow>
<TableRow>
<TextView
android:text=”Password:”
/>
<EditText
android:id=”@+id/txtPassword”
android:password=”true”
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:id=”@+id/chkRememberPassword”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Remember Password”
/>
</TableRow>
<TableRow>
<Button
android:id=”@+id/buttonSignIn”
android:text=”Log In” />
</TableRow>
</TableLayout>
RelativeLayout
<?xml version=”1.0” encoding=”utf-8”?>
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
/>
<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Comments”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
RelativeLayout
<EditText
android:id=”@+id/txtComments”
android:layout_width=”fill_parent”
android:layout_height=”170px”
android:textSize=”18sp”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
/>
RelativeLayout
<Button
android:id=”@+id/btnSave”
android:layout_width=”125px”
android:layout_height=”wrap_content”
android:text=”Save”
android:layout_below=”@+id/txtComments”
android:layout_alignRight=”@+id/txtComments”
/>
<Button
android:id=”@+id/btnCancel”
android:layout_width=”124px”
android:layout_height=”wrap_content”
android:text=”Cancel”
android:layout_below=”@+id/txtComments”
android:layout_alignLeft=”@+id/txtComments”
/>
</RelativeLayout>
Framelayout
• 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.
• You can, however, add multiple children to a FrameLayout and
control their position within the FrameLayout by assigning
gravity to each child, using the android:layout_gravity attribute.
Framelayout
FrameLayout Attributes
• android:id
• This is the ID which uniquely identifies the layout.
• android:foreground
• This defines the drawable to draw over the content and possible values may be a
color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
• android:foregroundGravity
• Defines the gravity to apply to the foreground drawable. The gravity defaults to fill.
Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.
• android:measureAllChildren
• Determines whether to measure all children or just those in the VISIBLE or
INVISIBLE state when measuring. Defaults to false.
Example
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Example
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView android:text="Frame Demo“
android:textSize="30px“
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
ScrollView
• In android, ScrollView is a kind of layout that is useful to add vertical or horizontal scroll bars to
the content which is larger than the actual size of layouts such
as linearlayout, relativelayout, framelayout, etc.
• Generally, the android ScrollView is useful when we have content that doesn’t fit our android
app layout screen. The ScrollView will enable a scroll to the content which is exceeding the
screen layout and allow users to see the complete content by scrolling.
• The android ScrollView can hold only one direct child. In case, if we want to add multiple views
within the scroll view, then we need to include them in another standard layout
like linearlayout, relativelayout, framelayout, etc.
• To enable scrolling for our android applications, ScrollView is the best option but we should not
use ScrollView along with ListView or Gridview because they both will take care of their own
vertical scrolling.
• In android, ScrollView supports only vertical scrolling. In case, if we want to
implement horizontal scrolling, then we need to use a HorizontalScrollView component.
• The android ScrollView is having a property called android:fillViewport, which is used to define
whether the ScrollView should stretch it’s content to fill the viewport or not.
Adapting to Display Orientation
• Screen Orientation, also known as screen rotation, is the attribute of
activity element in android. When screen orientation change from one
state to other, it is also known as configuration change.

Syntax:
<activity android:name="package_name.Your_ActivityName"
android:screenOrientation="orientation_type">
</activity>
Adapting to Display Orientation
• States of Screen orientation

There are various possible screen orientation states for any android application, such
as:

• ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
• ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
• ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
• ActivityInfo.SCREEN_ORIENTATION_USER
• ActivityInfo.SCREEN_ORIENTATION_SENSOR
• ActivityInfo.SCREEN_ORIENTATION_BEHIND
• ActivityInfo.SCREEN_ORIENTATION_NOSENSOR
• ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
• ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
• ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
change Screen orientation
• We will create two activities of different screen orientation.
• The first activity will be as “portrait” orientation and
• Second activity as “landscape” orientation state.
1.Creating the activities: There will be two activities and hence two
XML files, one for each activity.activity_main.xml: XML file for first
activity consist of constraint layout with Button and Text View in it.
This activity is in Landscape state.
2.activity_next.xml: XML file for second activity consist of constraint
layout with Text View in it. This activity is in Landscape state.
Anchoring Views
• As ARCore’s environmental understanding updates throughout
an AR experience, virtual objects can appear to drift away from
where they were placed. This can impact your app's realism and
user experience.
• Anchors ensure that objects appear to stay at the same position
and orientation in space, helping you maintain the illusion of
virtual objects placed in the real world.
anchors work
• To use anchors in your scene, your code should:
• Create anchors in the context of a Trackable (such as a Plane) or
the ARCore Session.
• Attach one or more objects to the anchor.
• Anchors can support different kinds of positional behavior in your
scene's objects.
• Determining anchor context and how many anchors you need for
your scene's objects depends on the positional behavior that your
AR scene requires. See the following sections for more
information.
Resizing and Repositioning
• Anchoring – This is the easiest way to anchor views to the four edges of the
screen. When the screen orientation changes, the views can anchor neatly to the
edges.
• Resizing and repositioning – These are simple techniques to ensure that views can
be handle changes in screen orientation.
• Layout_alignParentLeft – This property aligns the view to the left of the parent view.
• Layout_alignParentRight – This property aligns the view to the right of the parent
view.
• Layout_alignParentTop – This property aligns the view to the top of the parent view.
• Layout_alignParentBottom – This property aligns the view to the bottom of the
parent view.
• Layout_centerVertical – This property aligns the view at the center vertically within its
parent view.
• Layout_centerHorizontal – This property aligns the view at the center horizontally
within its parent view.
Managing Changes to Screen Orientation
• Sometimes handling the orientation changes for your Activity,
Fragment or AsyncTasks becomes most frustrating things to deal. If
orientation changes is not handle properly then it results unexpected
behavior of the application.
• When such changes occurs, Android restarts the running Activity
means it destroy and again created.
Why Screen Orientation
• When configurations changed during run time (such as screen
orientation, keyboard availability, and language), Android usually
destroys application’s existing Activity or Fragment and recreate it.
• Android does this so that application can reload its resources based on
the new configuration. The restart behavior helps application to adapt
new configurations by automatically reloading the application with
alternative resources that match the new device configuration.
• Proper handling of orientation changes makes rich user experience
(not lost UI state) for the application and it also avoiding memory
leaks.
Handle Screen Orientation
• To handle these configuration changes, Android provides callbacks to
save your application state before destroying either Activity or
Fragment. In the same it also provides to restore the application state
when it is recreating them.
• There are a different options to handle the orientation changes:
• 1. Lock screen orientation
• 2. Prevent Activity to recreated
• 3. Save basic state
• 4. Save complex objects
Lock screen orientation
• To lock the screen orientation change of any screen (activity) of your android application
makes your activity display only in one mode i.e. either Landscape or Portrait. This is the
simplest way to handle screen orientation but not generally recommended.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<application android:name="com.example.test.TestApplication"
android:label="@string/app_name"> <activity
android:name="com.example.test.activity.MainActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.example.test.activity.HomeActivity"
android:screenOrientation="landscape"/>
</application>
</manifest>
Prevent Activity to recreated
• Another most common solution to dealing with orientation changes by
setting the android:configChanges flag on your Activity in
AndroidManifest.xml. Using this attribute your Activities won’t be
recreated and all your views and data will still be there after
orientation change.
<activity
android:name="com.example.test.activity.MainActivity“
android:configChanges="orientation|screenSize|keyboardHidden"/>
Save basic state
• This is the most common situation to save the basic data of your Activity
or Fragment during orientation change. You can save Primitive data such
as String, Boolean, Integers or Parcelable objects in a Bundle during the
orientation change and read the same data when Activity recreated.
• Saving and restoring the data works using two Activity lifecycle methods
called onSaveInstanceState() and onRestoreInstanceState().
• To save the state information override onSaveInstanceState() method and
add key-value pairs to the Bundle object that is saved in the event that
your activity is destroyed unexpectedly. This method gets called
before onStop().
Save complex objects
• Override onRetainNonConfigurationInstance() and
getLastNonConfigurationInstance()
• Prior to Honeycomb’s release, the recommended means of transferring
active objects across Activity instances was to override
the onRetainNonConfigurationInstance()
and getLastNonConfigurationInstance() methods.
• After API level 13 these methods have been deprecated in favor of the
more Fragment’s setRetainInstance(boolean) capability, which
provides a much cleaner and modular means of retaining objects
during configuration changes.
Persisting State Information during
Changes in Configuration
1.onPause() – This method is always fired, whenever an activity is killed
or pushed into the background.

2.onSaveInstanceState() – This method is also fired, whenever an


activity is about to be killed or put into the background (same as
the onPause() method). However, unlike the onPause() method,
the onSaveInstanceState() method is not fired, when an activity is
being unloaded from the stack (when the user pressed the back
button) because there is no feed to restore its state later.
Detecting Orientation Changes
• Some device configurations can change during runtime (such as screen orientation,
keyboard availability, and when the user enables multi-window mode).
• When such a change occurs, Android restarts the running Activity ( onDestroy() is
called, followed by onCreate()).
• The restart behavior is designed to help your application adapt to new
configurations by automatically reloading your application with alternative
resources that match the new device configuration.
• To properly handle a restart, it is important that your activity restores its previous
state.
• You can use a combination of onSaveInstanceState(), ViewModel objects, and
persistent storage to save and restore the UI state of your activity across
configuration changes.
Detecting Orientation Changes
• To test that your application restarts itself with the application state intact, you
should invoke configuration changes (such as changing the screen orientation)
while performing various tasks in your application.
• Your application should be able to restart at any time without loss of user data
or state in order to handle events such as configuration changes or when the
user receives an incoming phone call and then returns to your application much
later after your application process may have been destroyed.
• To learn how you can restore your activity state, read about the Activity lifecycle.
• However, you might encounter a situation in which restarting your application
and restoring significant amounts of data can be costly and create a poor user
experience.
• In such a situation, you have two other options:
Detecting Orientation Changes
• Retain an object during a configuration change
• Allow your activity to restart when a configuration changes, but carry a
stateful object to the new instance of your activity.
• Handle the configuration change yourself
• It is not recommended to handle configuration changes yourself due to the
hidden complexity of handling the configuration changes. However, if you are
unable to preserve your UI state using the preferred options
(onSaveInstanceState(), ViewModels, and persistent storage) you can instead
prevent the system from restarting your activity during certain configuration
changes. Your app will receive a callback when the configurations do change
so that you can manually update your activity as necessary.
Controlling the Orientation of the Activity
• Occasionally you might want to ensure that your application is only
displayed in a certain orientation.For example, you may be writing a game
that should only be viewed in landscape mode.In this case, you can
programmatically force a change in orientation using the
setRequestOrientation() method of the Activity class:
• import android. content. Pm
import android.content.pm.ActivityInfo;
public class MainActivity extends Activity
{ /** Called when the activity is first created.
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---change to landscape mode---
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
Controlling the Orientation of the Activity
• To change to portrait mode, use the ActivityInfo
• To change to portrait mode, use the
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
constant:setRequestedOrientation(ActivityInfo.SCREEN_ORIE
NTATION_PORTRAIT);
• Besides using the setRequestOrientation() method, you can
also use the android:screenOrientation attribute on the
<activity> element in AndroidManifest.xml as follows to
constrain the activity to a certain orientation:
Controlling the Orientation of the Activity
<. xml version=”1. 0” encoding=”utf-8”
<?xml version=”1.0” encoding=”utf-8”?>
<manifest xmlns:android=” package=”net.learn2develop.Orientations”
android:versionCode=”1” android:versionName=”1.0”>
<application
<activity android:name=”.MainActivity”
android:screenOrientation=”landscape” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” /> </intent-
filter> </activity> </application>
<uses-sdk android:minSdkVersion=”9” /> </manifest>
Controlling the Orientation of the Activity
• The preceding example constrains the activity to a certain
orientation (landscape in this case) and prevents the activity
from being destroyed; that is, the activity will not be
destroyed and the onCreate() event will not be fired again
when the orientation of the device changes.
• Following are two other values that you can specify in
the android:screenOrientation attribute:
portrait — Portrait modesensor — Based on the
accelerometer
Adapter 
• Adapter in android acts as bridge between an AdapterView and the
underlying data for that view.
• The Adapter provides access to the data items.
• The Adapter is also responsible for making a View for each item in
the data set.
Adapter
• Data can be information obtained from database or server or it can be
already present in program.
• There are many subclasses of Adapter, for example CursorAdapter,
ArrayAdapteretc.
BaseAdapter

• BaseAdapter is an abstract class which implements ListAdapter and


SpinnerAdapter Interface.
• Hence, we may use it for implementing both ListView and Spinner.
• Following methods are necessary to implement for creating a subclass of
BaseAdapter:
• getCount() : int returns number of rows in list
• getItem(int position): Object returns Item object
• getItemId(int position): long returns the id of the item at position position
• getView(int arg0, View arg1, ViewGroup arg2): View
How getView() works?
• Adapters call the getView() method
which returns a view for each item
within the adapter view.
• The layout format and the
corresponding data for an item within
the adapter view is set in the getView()
method.
• Due to performance reasons, getView()
doesn’t returns a new View object every
time it is called.
• So what Android does is that it recycles
the views and reuses the view that goes
out of focus.
CursorAdapter
• Cursor is an interface which provides random read-write access to result set returned
by read write query. This interface has been explained in our previous post on
databases in android.
• CursorAdapter is a subclass of BaseAdapter. It is used to bind cursor data qureied
from database to AdapterView. Cursor adapter has following abstract methods,
• newView(Context context, Cursor cursor, ViewGroup parent): View This method
creates new AdapterView to hold data.
• bindView(View view, Context context, Cursor cursor): void In this method
CursorAdapter just elements to list’s view.
• SimpleCursorAdapter is subclass of CursorAdapter. If we use it, we don’t have to
create separate Adapter’s subclass. Here is a sample code that shows how do we
attach this to listview.
Array Adapter
• Array Adapter is subclass of BaseAdapter. It is used to bind data in
arrayList to AdapterView.
• In this type of adapter, we pass List, context of activity and layout of
entry as attribute, but layout of entry can be only those which are
already present in the library. We associate an adapter with View.
Custom Adapters for ListView
• Custom Adapter is used when we want to design and add more UI
components to an item of ListView or GridView.
• We build this class on our own. This class extends Adapter or
Adapter’s subclass. In the getView() method of class, we may set
custom content View.

You might also like