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

Unit 3

Uploaded by

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

Unit 3

Uploaded by

Ripal Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Unit 3

Working with the User Interface Using Vies and ViewGroups


Android UI
 Android provides a variety of Pre-built UI components.
 Layout objects and UI controls that allow you to build the graphical user interface for
your app.
 Android also provides other UI modules for special interfaces such as dialogs,
notifications, and menus.
View Group
 A ViewGroup is a special view that can contain other views (called children.)
 The view group is the base class for layouts and views containers.
 It’s child can be Views or ViewGroup.
Views
 View 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.
 All of the views in a window are arranged in a single tree.
 View is the base class for widgets, which are used to create interactive UI
components (buttons, text fields, etc.)
Layouts
 A layout defines the structure for a user interface in your 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.
 Layout(ViewGroup) is an invisible container that defines the layout structure for View
and other Layout(ViewGroup) objects.
 It provide a different layout structure, such as LinearLayout or ConstraintLayout.
 Linear Layout
 Relative Layout
 Frame Layout
 Table Layout
 Grid Layout
 Constraint Layout
Linear Layout
 LinearLayout is a view group that aligns all children in a single direction, vertically
or horizontally.
 You can specify the layout direction with the android:orientation attribute.
 Linear Layout can be created in two direction: Horizontal & Vertical.
 LinearLayout also supports assigning a weight to individual children with the
android:layout_weight attribute.
 This attribute assigns an important 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.
 To control how linear layout aligns all the views it contains, set a value
for android:gravity.
 The following snippet shows how to include a linear layout in your layout
XML file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="horizontal"
android:gravity="center">

<!-- Include other widget or layout tags here. These are considered "child views" or "children" of
the linear layout -->

</LinearLayout>
Relative Layout
 RelativeLayout is a view group that displays child views in relative positions.
 The position of each view can be specified as relative to sibling elements or in
positions relative to the parent RelativeLayout area.
 As it allows us to position the component anywhere, it is considered as most
flexible layout.
 Relative layout is the most used layout after the Linear Layout in Android.
 In Relative Layout, you can use “above, below, left and right” to arrange the
component’s position in relation to other component.
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<Spinner
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
<Spinner
android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />
TableLayout
 TableLayout is a ViewGroup that displays child View elements in rows and columns.
 TableLayout positions its children into rows and columns.
 TableLayout containers do not display border lines for their rows, columns, or cells.
 The table will have as many columns as the row with the most cells.
 A table can leave cells empty.
 TableRow objects are the child views of a TableLayout (each TableRow defines a
single row in the table).
 Each row has zero or more cells, each of which is defined by any kind of other View.
So, the cells of a row may be composed of a variety of View objects, like ImageView
or TextView objects.
 A cell may also be a ViewGroup object (for example, you can nest another
TableLayout as a cell).
 <?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns=“1”>
<TableRow>
<TextView
android:text="@string/table_layout_4_open"
android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_open_shortcut"
android:gravity="right"
android:padding="3dip" />
</TableRow>

<TableRow>
<TextView
android:text="@string/table_layout_4_save"
android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_save_shortcut"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout>
GridLayout
 A layout that places its children in a rectangular grid.
 The grid is composed of a set of infinitely thin lines that separate the viewing
area into cells.
 Children occupy one or more contiguous cells, as defined by their rowSpec
and columnSpec layout parameters.
Attributes Description
android:columnCount The maximum number of columns to create when automatically positioning children.
android:columnOrderPreserved When set to true, forces column boundaries to appear in the same order as column
indices.
android:orientation The orientation property is not used during layout.
android:rowCount The maximum number of rows to create when automatically positioning children.
android:rowOrderPreserved When set to true, forces row boundaries to appear in the same order as row indices.
<?xml version="1.0" encoding="utf-8"?> <EditText android:ems="10" />
<TextView
<GridLayout android:text="Password:"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_column="0"
android:layout_width="match_parent"
android:layout_gravity="right" />
android:layout_height="match_parent" <EditText android:ems="8" />
android:useDefaultMargins="true" <Space android:layout_row="4"
android:alignmentMode="alignBounds" android:layout_column="0"
android:columnOrderPreserved="false" android:layout_columnSpan="3"
android:layout_gravity="fill" />
android:columnCount="4" >
<Button android:text="Next"
android:layout_row="5"
<TextView android:text="Email setup“ android:layout_column="3" />
android:textSize="32dip" </GridLayout>
android:layout_columnSpan="4"
android:layout_gravity="center_horizontal" />
<TextView android:text="You can configure email in just a few
steps:“
android:textSize="16dip"
android:layout_columnSpan="4"
android:layout_gravity="left" />
<TextView android:text="Email address:“
android:layout_gravity="right" />
Frame Layout
 Frame Layout is designed to block out an area on the screen to
display a single item.
 It is used to specify the position of Views.
 Generally, FrameLayout should be used to hold a single child
view.
 It contains Views on the top of each other to display only
single View inside the FrameLayout.
 You can, add multiple children to a FrameLayout and control
their position by using gravity attribute.
 In this the child views are added in a stack and the most recently
added child will show on the top.
 The size of the FrameLayout is the size of its largest child (plus
padding), visible or not (if the FrameLayout's parent permits).
FrameLayout
ConstraintLayout
 similar to RelativeLayout in that all views are laid out according to relationships
between sibling views and the parent layout, but it's more flexible
than RelativeLayout.
 You can build your layout with ConstraintLayout entirely by dragging instead of
editing the XML.
 To define a view's position in ConstraintLayout, you add at least one horizontal
and one vertical constraint for the view.
 Each constraint represents a connection or alignment to another view, the parent
layout, or an invisible guideline.
 Each constraint defines the view's position along the vertical or horizontal axis.
 Each view must have a minimum of one constraint for each axis, but often more
are necessary.
TabLayout
 TabLayout is used to implement horizontal tabs.
 Population of the tabs to display is done through TabLayout.Tab instances.
 Create tabs via newTab() From there we can change the tab's label or icon via
TabLayout.Tab.setText(int).
 A TabLayout can be setup with a ViewPager
 Dynamically create TabItems based on the number of pages, their titles, etc.
 Synchronize the selected tab and tab indicator position with page swipes.
 There are two types of tabs: Fixed tabs, Scrollable tabs.
 1) Fixed tabs display all tabs on one screen, with each tab at a fixed width.
 2) Scrollable tabs are displayed without fixed widths. They are scrollable, such
that some tabs will remain off-screen until scrolled.
Android UI Controls
 There are number of Ul controls provided by Android that allow you to build
the graphical user interface for your app.
UI Control Description
TextView This control is used to display text to the user.
EditText EditText is a predefined subclass of TextView that includes rich editing capabilities.
AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText, except that it shows a
list of completion suggestions automatically while the user is typing.

Button A push-button that can be pressed, or clicked, by the user to perform an action.
ImageButton An ImageButton is an AbsoluteLayout which enables you to specify the exact location
of its children. This shows a button with an image (instead of text) that can be pressed
or clicked by the user.

CheckBox An on/off switch that can be toggled by the user. You should use check box when
presenting users with a group of selectable options that are not mutually exclusive.
UI Control Description

ToggleButton An on/off button with a light indicator.

RadioButton The RadioButton has two states: either checked or unchecked.

RadioGroup A RadioGroup is used to group together one or more RadioButtons

ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks, such as
when you are performing a task in the background.

Spinner A drop-down list that allows users to select one value from a set.

TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour mode
or AM/PM mode.

DatePicker The DatePicker view enables users to select a date of the day.
TextView
 TextView is a UI Component that displays the text to the user on their Display Screen .
Attribution Description
android:id This is the ID which uniquely identifies the control.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text when the text is smaller than the view.
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:text Text to display in view.
android:textAllCaps Make the text in Capital. 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:textStyle Style (bold, italic, bolditalic) for the text. You can use or more of the 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 values separated
by '|'. normal – 0, sans – 1, serif – 2, monospace – 3.
EditText
 A EditText is an overlay over TextView that configures itself to be editable.
 It is the predefined subclass of TextView that includes rich editing capabilities.
Attribute Description
android:autoText 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:editable If set, specifies that this TextView has an input method.


android:background This is a drawable to use as the background.
android:inputType The type of data being placed in a text field. Phone, Date, Time, Number, Password etc.
android:hint Hint text to display when the text is empty.
android:focusable It specifies that this edittext gets auto focus or not.
AutoCompleteTextView
 AutoCompleteTextView is view that similar to EditText, except that it shows a
list of completion suggestions automatically while the user is typing.
 The list of suggestions is displayed in drop down menu. The user can choose
an item from there to replace the content of box with.
Attribute Description

android:completionHint This defines the hint displayed in the drop down menu

android:completionHintView This defines the hint view displayed in the drop down menu

android:completion Threshold This defines the number of characters that the user must type before
completion suggestions are displayed in a drop down menu.

android:dropDownAnchor This is the View to anchor the auto-complete dropdown to.


AutoCompleteTextView (Cont…)

Attribute Description

android:dropDownHeight This specifies the basic height of the dropdown

android:dropDownHorizontalOff The amount of pixels by which the drop down should be


set offset horizontally.

android:dropDown Selector This the selector in drop down list.

android:dropDown The amount of pixels by which the drop down should be


VerticalOffset offset vertically.
android:dropDownWidth This specifies the basic width of the dropdown.

android:popupBackground This sets the background.


Button
 A Button which can be pressed, or clicked, by the user to perform an action.
 To specify an action when the button is pressed, set a click listener on the
button object in the corresponding activity code.
 Every button is styled using the system's default button background it can
customize.
Attribute Description

android:text This is used to display text on button.

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

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.
ImageButton
 Displays a button with an image (instead of text) that can be pressed or clicked
by the user.
 By default, an ImageButton looks like a regular Button, with the standard
button background that changes color during different button states.
ToggleButton
 A ToggleButton displays checked/unchecked states as a button. It is basically
an on/off button with a light indicator.

Attributes Description
android:disabledAlpha The alpha to apply to the indicator when
disabled.

android:textOff The text for the button when it is not


checked.

android:textOn The text for the button when it is


checked.
CheckBox
 A checkbox is a specific type of two-states button that can be either checked or
unchecked.
 A example usage of a checkbox inside your activity would be the following:
 public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.content_layout_id);

final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);


if (checkBox.isChecked()) {
checkBox.setChecked(false);
}
}
}
RadioButton
 A radio button is a two-states button that can be either checked or unchecked.
 When the radio button is unchecked, the user can press or click it to check it.
However, contrary to a CheckBox, a radio button cannot be unchecked by the
user once checked.
 Radio buttons are normally used together in a RadioGroup.
 When several radio buttons live inside a radio group, checking one radio
button uncheck all the others.
RadioGroup
 This class is used to create a multiple-exclusion scope for a set of radio
buttons. Checking one radio button that belongs to a radio group unchecks any
previously checked radio button within the same group.
 Intially, all of the radio buttons are unchecked.
 The selection is identified by the unique id of the radio button as defined in the
XML layout file.
 android:checkedButton
 The id of the child radio button that should be checked by default within this
radio group.
 <?xml version="1.0" encoding="utf-8"?>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pirates"/>
<RadioButton android:id="@+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ninjas"/>
</RadioGroup>
ProgressBar
 A user interface element that indicates the progress of an operation.
 Progress bar supports two modes to represent progress: determinate, and
indeterminate.
 Indeterminate Progress
 Use indeterminate mode for the progress bar when you do not know how long an
operation will take.
 Indeterminate mode is the default for progress bar and shows a cyclic animation
without a specific amount of progress indicated.
<ProgressBar
android:id="@+id/indeterminateBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
 Determinate Progress
 Use determinate mode for the progress bar when you want to show that a specific quantity of
progress has occurred.
 For example, the percent remaining of a file being retrieved, the amount records in a batch
written to database, or the percent remaining of an audio file that is playing.
 To indicate determinate progress, you set the style of the progress bar to
R.style.Widget_ProgressBar_Horizontal and set the amount of progress.
 The following example shows a determinate progress bar that is 25% complete:

<ProgressBar
android:id="@+id/determinateBar" style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress="25"/>
 You can update the percentage of progress displayed by using the setProgress(int) method, or by
calling incrementProgressBy(int) to increase the current progress completed by a specified
amount.
Spinner
 A view that displays one child at a time and lets the user pick among them.
 Android Spinner is a view similar to the dropdown list which is used to
select one option from the list of options.
 It provides an easy way to select one item from the list of items and it
shows a dropdown list of all values when we click on it.
 The default value of the android spinner will be the currently selected value.
 By using Adapter we can easily bind the items to the spinner objects.
 You can add a spinner to your layout with the Spinner object.
<Spinner
android:id="@+id/planets_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
String[] planets_array = {“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”,
“Uranus”, “Neptune”};
protected void onCreate(Bundle savedInstanceState) simple_spinner_item is the
default layout for the spinner's
{ appearance
Spinner spinner = (Spinner) findViewById(R.id.planets_spinner);
spinner.setOnItemSelectedListener(this);
ArrayAdapter adapter = new ArrayAdapter( this, android.R.layout.simple_spinner_item, planets_array);

//to specify the layout the adapter uses to display the list of spinner choices.
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// Apply the adapter to the spinner.


spinner.setAdapter(adapter); simple_spinner_dropdown_item is
the standard layout defined by the
} platform.
Scroll View
 A view group that allows the view hierarchy placed within it to be scrolled.
 Scroll view may have only one direct child placed within it.
 To add multiple views within the scroll view, make the direct child you add a
view group,
 for example LinearLayout, and place additional views within that LinearLayout.
 Scroll view supports vertical scrolling only. For horizontal scrolling, use
HorizontalScrollView instead.
 android:fillViewport: Defines whether the scrollview should stretch its content
to fill the viewport.
Card View
 CardView is a new widget in Android that can be used to display any sort of data by
providing a rounded corner layout along with a specific elevation.
 The main usage of CardView is that it helps to give a rich feel and look to the UI
design.
 These cards have a default elevation above their containing view group, so the
system draws shadows below them.
 Information inside cards that have a consistent look across the platform.
 It can be used for creating items in ListView or inside RecyclerView.
Attribute Description
card_view:cardBackgroundColor Can set background color.
card_view:cardCornerRadius To set Radius or card corner
card_view:cardElevation To set elevation to tha card
card_view:cardUseCompatPadding Set compatible padding to cardview based on radius and
elevation
Adapter
 An Adapter object acts as a bridge between an AdapterView and the underlying
data for that view.
 In Android development, any time we want to show a vertical list of scrollable
items we will use a ListView which has data populated using an Adapter.
 The simplest adapter to use is called an ArrayAdapter because the adapter converts
an ArrayList of objects into View items loaded into the ListView container.
 The ArrayAdapter fits in between an ArrayList (data source) and the ListView
(visual representation)
 When your ListView is connected to an adapter, the adapter will instantiate rows
until the ListView has been fully populated with enough items to fill the full height
of the screen. At that point, no additional row items are created in memory.
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView
 ListView is a view which groups several items and display them in vertical
scrollable 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.
 An adapter actually acts as a bridge between UI components and the data
source that fill data into UI Component.
Attribute Description
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.
<ListView android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
-----------------------------------------------------------------------------
.java file:

ListView l;
String[] planets_array = {“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune”};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list_view);
ArrayAdapter<String> arr;
arr = new ArrayAdapter<String>( this, R.layout.support_simple_spinner_dropdown_item, planets_array);
l.setAdapter(arr);
}
Dialog
 A dialog is a small window that prompts the user to make a decision or enter
additional information.
 A dialog doesn't fill the screen and is normally used for modal events that
require users to take an action before they can proceed.
 The Dialog class is the base class for dialogs, but don't
instantiate Dialog directly.
 Instead, use one of the following subclasses:
 AlertDialog: A dialog that can show a title, up to three buttons,
a list of selectable items, or a custom layout.
 DatePickerDialog or TimePickerDialog: A dialog with a predefined

UI that lets the user select a date or time.


AlertDialog
 A subclass of Dialog that can display one, two or three buttons.
 If you only want to display a String in this dialog box, use the setMessage()
method.
 there are three regions of an alert dialog:
 Title: this is optional and only used when the content area is occupied by a detailed
message, list, or custom layout. If you need to state a simple message or question, you
don't need a title.
 Content area: this can display a message, list, or other custom layout.
 Action buttons: there can be up to three action buttons in a dialog.
 To build an AlertDialog, do the following:
// 1. Instantiate an AlertDialog.Builder with its constructor.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// 2. Chain together various setter methods to set the dialog characteristics.


builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);

// 3. Get the AlertDialog.


AlertDialog dialog = builder.create();

//4. To Show the AlertDialog box:


dialog.show();
 To add action buttons
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Add the buttons.
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User taps OK button.
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancels the dialog.
}
});
// Set other dialog properties.
...

// Create the AlertDialog.


AlertDialog dialog = builder.create();
pickers
 Android provides controls for the user to pick a time or date as ready-to-use
dialogs.
 These pickers provide controls for selecting each part of the time (hour,
minute, AM/PM) or date (month, day, year).
 Using these pickers helps ensure that your users can pick a time or date that is
valid, formatted correctly, and adjusted to the user's locale.
TimePicker
 TimePicker Dialog is used in many applications where we have to book
appointments based on a specific time.
 This widget is seen in the applications where we have to select specific time
slots.
 To creates a new time picker dialog:
public TimePickerDialog (Context context, TimePickerDialog.OnTimeSetListener listener, int
hourOfDay, int minute, boolean is24HourView)
 TimePickerDialog.OnTimeSetListener: This callback interface used to indicate the user
is done filling in the time (e.g. they clicked on the 'OK' button).
DatePicker
 DatePicker dialog is seen used in many android applications where we have to
select the date.
 This widget is mostly seen in the hotel reservation applications for travel
booking applications.
 With the help of this widget, we can simply pick the date from the DatePicker
dialog.
 Creates a new date picker dialog for the specified date using the parent
context's default date picker dialog theme:
DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener listener, int
year, int month, int dayOfMonth)
 DatePickerDialog.OnDateSetListener: This listener used to indicate the user has
finished selecting a date.
Menus
 Menus are a common user interface component in many types of apps.
 To provide a familiar and consistent user experience, use the Menu APIs to present
user actions and other options in your activities.
 For all menu types, Android provides a standard XML format to define menu items.
 To define a menu, create an XML file inside your project's res/menu/ directory and
build the menu with the following elements:
 <menu> :Defines a Menu, which is a container for menu items. A <menu> element must be
the root node for the file, and it can hold one or more <item> and <group> elements.
 <item> :Creates a MenuItem, which represents a single item in a menu. This element can
contain a nested <menu> element to create a submenu.
 <group> :An optional, invisible container for <item> elements. It lets you categorize menu
items so they share properties, such as active state and visibility.
 <?xml version="1.0" encoding="utf-8"?>  <?xml version="1.0" encoding="utf-8"?>
<menu <menu
xmlns:android="http://schemas.android.com/apk xmlns:android="http://schemas.android.com/apk/re
/res/android"> s/android">
<item android:id="@+id/new_game" <item android:id="@+id/file"
android:icon="@drawable/ic_new_game" android:title="@string/file" >
android:title="@string/new_game" <!-- "file" submenu -->
app:showAsAction="ifRoom"/> <menu>
<item android:id="@+id/help" <item android:id="@+id/create_new"
android:icon="@drawable/ic_help" android:title="@string/create_new" />
android:title="@string/help" /> <item android:id="@+id/open"
</menu> android:title="@string/open" />
</menu>
</item>
</menu>
 There are 3 fundamental types of menus as below:
1. Options menu and app bar
 The options menu is the primary collection of menu items for an activity.
 It's where you should place actions that have a global impact on the app, such as
"Search," "Compose email," and "Settings.

2. Context menu and contextual action mode


 A context menu is a floating menu that appears when the user performs a touch &
hold on an element.
 It provides actions that affect the selected content or context frame.
 The contextual action mode displays action items that affect the selected content in
a bar at the top of the screen and allows the user to select multiple items.
3. Popup menu:
 A popup menu displays a vertical list of items that's anchored to the view that invokes
the menu.
 It's good for providing an overflow of actions that relate to specific content or to
provide options for the second part of a command.
 Actions in a popup menu don't directly affect the corresponding content—that's what
contextual actions are for.
 Rather, the popup menu is for extended actions that relate to regions of content in your
activity.
Options Menu
 The options menu is the primary collection of menu items for an activity.
 Options Menu Generally placed on action bar.
 We can declare items for the options menu from either Activity or a Fragment.
 Re-order the menu items with the android:orderInCategory attribute from xml file
menu item.
 To specify the options menu for an activity, override onCreateOptionsMenu().
 In this method, you can inflate your menu resource (defined in XML) into the Menu.
 If you want to modify the options menu based on events that occur during the activity
lifecycle, you can do so in the onPrepareOptionsMenu() method.
 You can also add menu items using add() and retrieve items with findItem().
 When the user clicks a menu item from the options menu onOptionsItemSelected()
method is used to get callback.
Contextual Menu
 A contextual menu offers actions that affect a specific item or context frame in
the UI.
 You can provide a context menu for any view, but they are most often used for
items in a RecylerView or other view collections in which the user can perform
direct actions on each item.
 There are two ways to provide contextual actions:
 In a floating context menu. A menu appears as a floating list of menu items, similar to a
dialog, when the user performs a touch & hold on a view that declares support for a
context menu. Users can perform a contextual action on one item at a time.
 In the contextual action mode. This mode is a system implementation of ActionMode that
displays a contextual action bar, or CAB, at the top of the screen with action items that
affect the selected item(s). When this mode is active, users can perform an action on
multiple items at once, if your app supports that.
 To provide a floating context menu, do the following:
 Register the View the context menu is associated with by calling
registerForContextMenu() and passing it the View.
 Implement the onCreateContextMenu() method in your Activity or Fragment.
 When the user selects a menu item, the system calls onContextItemSelected() method
so you can perform the appropriate action.
 contextual action bar, or CAB
Popup Menu
 A PopupMenu is a modal menu anchored to a View. It appears below the
anchor view if there is room, or above the view otherwise.
 It's useful for the following:
 Providing an overflow-style menu for actions that relate to specific content, such as
Gmail's email headers
 Providing a second part of a command sentence, such as a button marked
Add that produces a popup menu with different Add options.
 Providing a menu similar to a Spinner that doesn't retain a persistent
selection.
 To show the popup menu:
 Instantiate a PopupMenu with its constructor, which takes the current app Context and
the View to which the menu is anchored.
 Use MenuInflater to inflate your menu resource into the Menu object returned by
PopupMenu.getMenu().
 Call PopupMenu.show().
 For example, here's a button that shows a popup menu:
<ImageButton
android:id="@+id/dropdown_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/descr_overflow_button"
android:src="@drawable/arrow_drop_down" />
 The activity can then show the popup menu like this:
 findViewById(R.id.dropdown_menu).setOnClickListener(v -> {
PopupMenu popup = new PopupMenu(this, v);
popup.getMenuInflater().inflate(R.menu.actions, popup.getMenu());
popup.show();
});
 To perform an action when the user selects a menu item, implement the
PopupMenu.OnMenuItemClickListener interface and register it with
your PopupMenu by calling setOnMenuItemclickListener().
 When the user selects an item, the system calls the onMenuItemClick() callback
in your interface.
 The menu is dismissed using PopupMenu.OnDismissListener when the user
selects an item or taps outside the menu area.
References
 https://developer.android.com/reference/android/widget/
 https://developer.android.com/develop/ui/views/components/dialogs
 https://www.geeksforgeeks.org/

You might also like