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

User Interface - Android

The document discusses Android UI and components, including: - Views and ViewGroups are used to create Android UIs, with views as widgets and ViewGroups grouping views. - Common views include TextView, Button, ImageButton and EditText. Common ViewGroups include LinearLayout and RelativeLayout. - Layouts like LinearLayout, RelativeLayout and FrameLayout are used to position views. TabLayout is used for horizontal tabs. - Attributes like layout_width, layout_height and orientation are used to configure views and ViewGroups.

Uploaded by

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

User Interface - Android

The document discusses Android UI and components, including: - Views and ViewGroups are used to create Android UIs, with views as widgets and ViewGroups grouping views. - Common views include TextView, Button, ImageButton and EditText. Common ViewGroups include LinearLayout and RelativeLayout. - Layouts like LinearLayout, RelativeLayout and FrameLayout are used to position views. TabLayout is used for horizontal tabs. - Attributes like layout_width, layout_height and orientation are used to configure views and ViewGroups.

Uploaded by

Akhed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

UNIT 4: Android UI And Component

using Fragments
• Create Android UI
• Working with Layout
• Create Custom Layouts
• Work with UI Components and Events
• Material Design Toolbar
• Tab Layout, Recycler View and Card View
• Android Menus

Prof. Urmi Desai, SCET CO


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 textboxes.
• 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.

Prof. Urmi Desai, SCET CO


Different Types of Views
• Basic views — Commonly used views
such as the TextView, EditText, and Button
views etc
• Picker views — Views that enable users
to select from a list, such as the
TimePicker and DatePicker views etc
• List views — Views that display a long list
of items, such as the ListView and the
SpinnerView views etc

Prof. Urmi Desai, SCET CO


Different types of layouts

• Android supports the following Layouts:


• Linear Layout
• Absolute Layout
• Table Layout
• Relative Layout
• Frame Layout
• Tab Layout

Prof. Urmi Desai, SCET CO


USING BASIC VIEWS
• TextView - Used to display text to the user.
• Button — Represents a push-button widget
• ImageButton — Similar to the Button view, except that
it also displays an image
• EditText — A subclass of the TextView view that
allows users to edit its text content
• CheckBox — A special type of button that has two
states: checked or unchecked
• RadioGroup and RadioButton — The RadioButton
has two states: either checked or unchecked. A
RadioGroup is used to group together one or more
RadioButton views, thereby allowing only one
RadioButton to be checked within the RadioGroup.
• ToggleButton — Displays checked/unchecked states
using a light indicator

Prof. Urmi Desai, SCET CO


Common Attributes Used in Views and ViewGroups

Prof. Urmi Desai, SCET CO


Common Attributes Used in Views and
ViewGroups
• match_parent/fill_parent(API 8)
• When you set layout width and height as
match_parent, it will occupy the complete
area that the parent view has, i.e. it will be
as big as the parent.
• wrap_content
• If you set layout width or height as
wrap_content it will use space big enough
for its contents to get enclosed.
Prof. Urmi Desai, SCET CO
Units Of Measurement

Prof. Urmi Desai, SCET CO


TextView and Button view

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Layouts
1.LinearLayout : is a ViewGroup that aligns all children in
a single direction, vertically or horizontally
2.RelativeLayout : is a ViewGroup that displays child
views in relative positions
3.AbsoluteLayout : allows us to specify the exact location
of the child views and widgets
4.TableLayout : is a view that groups its child views into
rows and columns
5.FrameLayout : is a placeholder on screen that is used
to display a single view
6.TabLayout : TabLayout is introduced in design support
library to implement tabs.

Prof. Urmi Desai, SCET CO


Linear Layout
• In android, LinearLayout is a ViewGroup subclass which is used to
render all child View instances one by one either
in Horizontal direction or Vertical direction based on
the orientation property.
• In android, we can specify the linear layout orientation
using android:orientation attribute.
• Following is the pictorial representation of linear layout in android
applications. In LinearLayout, the child View instances arranged
one by one, so the horizontal list will have only one row of multiple
columns and vertical list will have one column of multiple rows.

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Relative Layout
• In android, RelativeLayout is a ViewGroup which is used to
specify the position of child View instances relative to each
other (Child A to the left of Child B) or relative to the parent
(Aligned to the top of parent).
• In android, RelativeLayout is very useful to design user
interface because by using relative layout we can eliminate
the nested view groups and keep our layout hierarchy flat,
which improves the performance of application.

Prof. Urmi Desai, SCET CO


Attribute Description
layout_alignParentTop If it specified “true”, the top edge of view will match the top edge of the parent.
layout_alignParentBottom If it specified “true”, the bottom edge of view will match the bottom edge of
parent.
layout_alignParentLeft If it specified “true”, the left edge of view will match the left edge of parent.
layout_alignParentRight If it specified “true”, the right edge of view will match the right edge of the
parent.
layout_centerInParent If it specified “true”, the view will be aligned to the centre of parent.
layout_centerHorizontal If it specified “true”, the view will be horizontally centre aligned within its
parent.
layout_centerVertical If it specified “true”, the view will be vertically centre aligned within its parent.
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.
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 the end of the
specified view id.Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Table Layout
• In android, TableLayout is a ViewGroup subclass that is
used to display the child View elements in rows and
columns.
• In android, TableLayout will position its children
elements into rows and columns and it won’t display
any border lines for rows, columns or cells.
• The TableLayout in android will work same as the
HTML table and the table will have as many columns as
the row with the most cells. The TableLayout can be
explained as <table> and TableRow is like <tr> element.

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Absolute Layout
• An Absolute Layout lets you specify exact locations (x/y
coordinates) of its children. Absolute layouts are less flexible
and harder to maintain than other types of layouts without
absolute positioning.

android:layout_x
This specifies the x-
coordinate of the view.
android:layout_y
This specifies the y-
coordinate of the view.

• Absolute layout are harder to maintain for different mobile


screen sizes than other types of layouts because we set the
exact location of a child view or called component.

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
Framelayout
• Framelayout is a ViewGroup subclass that is used to specify
the position of View instances it contains on the top of each
other to display only single View inside the FrameLayout.
• In simple manner, we can say FrameLayout is designed to
block out an area on the screen to display a single item.

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
ScrollView (Horizontal, Vertical)
• 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.
• ScrollView supports only vertical scrolling. In case, if
we want to implement horizontal scrolling, then we
need to use a HorizontalScrollView component.

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
TabLayout
• TabLayout is used to implement horizontal tabs. TabLayout is
released by Android after the deprecation of ActionBar.TabListener
(API level 21).
• TabLayout is introduced in design support library to implement
tabs.
• Tabs are created using newTab() method of TabLayout class. The
title and icon of Tabs are set
through setText(int) and setIcon(int) methods of TabListener
interface respectively. Tabs of layout are attached over TabLayout
using the method addTab(Tab) method.
– TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
– tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
– tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
– tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.viewPager);

tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Sport"));
tabLayout.addTab(tabLayout.newTab().setText("Movie"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

final Pager adapter = new Pager(this,getSupportFragmentManager(),


tabLayout.getTabCount());
viewPager.setAdapter(adapter);

viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
} Prof. Urmi Desai, SCET CO
public class Pager extends FragmentPagerAdapter {

private Context myContext;


int totalTabs;

public Pager(Context context, FragmentManager fm, int totalTabs) {


super(fm);
myContext = context;
this.totalTabs = totalTabs;
}
public Fragment getItem(int position) {
switch (position) {
case 0:
First First = new First();
return First;
case 1:
Second second = new Second();
return second;
case 2:
Third third = new Third();
return third;
default:
return null; Prof. Urmi Desai, SCET CO
}
Toast
• Andorid Toast can be used to display
information for the short period of time. A
toast contains message to be displayed quickly
and disappears after sometime.
• The android.widget.Toast class is the subclass
of java.lang.Object class.

Prof. Urmi Desai, SCET CO


Method Description

public static Toast makeText(Context makes the toast containing text and
context, CharSequence text, int duration.
duration)
public void show() displays toast.
public void setMargin (float changes the horizontal and vertical
horizontalMargin, float verticalMargin) margin difference.

Constant Description

public static final int displays view for the long duration
LENGTH_LONG of time.
public static final int displays view for the short
LENGTH_SHORT duration of time.

Toast.makeText(getApplicationContext(),"Hello World",Toast.LENGTH_SHORT).show();
Another code:
Toast toast=Toast.makeText(getApplicationContext(),"Hello World",Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
Prof. Urmi Desai, SCET CO
Handling View Events
• For Button-
• Button btnOpen = (Button) findViewById(R.id.btnOpen);
• btnOpen.setOnClickListener(new View.OnClickListener() {
• public void onClick(View v) {
• DisplayToast(“You have clicked the Open button”);
• } });
• For Checkbox-
• CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave);
• checkBox.setOnClickListener(new View.OnClickListener()
• {
• public void onClick(View v) {
• if (((CheckBox)v).isChecked())
• DisplayToast(“CheckBox is checked”);
• else
• DisplayToast(“CheckBox is unchecked”); } CO
Prof. Urmi Desai, SCET });
Handling View Events
• For radiobutton
• RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
• radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
• {
• public void onCheckedChanged(RadioGroup group, int checkedId) {
• RadioButton rb1 = (RadioButton) findViewById(R.id.rdb1);
• if (rb1.isChecked()) {
• DisplayToast(“Option 1 checked!”);
• } else {
• DisplayToast(“Option 2 checked!”); } } });
• For togglebutton
• ToggleButton toggleButton =
• (ToggleButton) findViewById(R.id.toggle1);
• toggleButton.setOnClickListener(new View.OnClickListener()
• {
• public void onClick(View v) {
• if (((ToggleButton)v).isChecked())
• DisplayToast(“Toggle button is On”);
• else
• Prof. Urmi
DisplayToast(“Toggle button is Off”); } Desai, SCET});
CO

• @Override
• protected void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• setContentView(R.layout.activity_main);
• Button button = findViewById(R.id.button);
• EditText editText = findViewById(R.id.editText);
• button.setOnClickListener(new View.OnClickListener() {
• @Override
• public void onClick(View view) {
• String s=editText.getText().toString();
• Toast.makeText(getApplicationContext(),s,Toast.
LENGTH_SHORT).show();
• }
• });
• } Prof. Urmi Desai, SCET CO
• There is another way to handle view events. Using the
Button as an
• example, you can add an attribute called onClick to it:
• <Button android:id=”@+id/btnSave”
• android:layout_width=”fill_parent”
• android:layout_height=”wrap_content”
• android:text=”save”
• android:onClick=”btnSaved_clicked”/>

• public class BasicViews1Activity extends Activity {


• public void btnSaved_clicked (View view) {
• DisplayToast(“You have clicked the Save button1”);
• } Prof. Urmi Desai, SCET CO
Others Views
• Picker view
• List view
• Progressbar vew
• Ratingbar view
• Auto complete textview
• Recycle view
• Card view

Prof. Urmi Desai, SCET CO


Picker View(date and time)
• Android DatePicker is a widget to select date. It allows
you to select date by day, month and year.
• The android.widget.DatePicker is the subclass of
FrameLayout class.
• <DatePicker
• android:id="@+id/datePicker"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:layout_above="@+id/textView1"
• android:layout_centerHorizontal="true"
• android:layout_marginBottom="36dp" />

Prof. Urmi Desai, SCET CO


Picker View(date and time)
• picker=(DatePicker)findViewById(R.id.datePick
er);
• picker.getMonth()
• picker.getDayOfMonth()
• picker.getYear()

Prof. Urmi Desai, SCET CO


Picker View(date and time)
• Android TimePicker widget is used to select date. It allows
you to select time by hour and minute. You cannot select
time by seconds.
• The android.widget.TimePicker is the subclass of
FrameLayout class.
• <TimePicker
• android:id="@+id/timePicker"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:layout_above="@+id/textView1"
• android:layout_centerHorizontal="true"
• android:layout_marginBottom="36dp" />

Prof. Urmi Desai, SCET CO


Picker View(date and time)
• timepicker=(TimePicker)findViewById(R.id.tim
ePicker);
• timepicker.setIs24HourView(true);
• timepicker.getCurrentHour()
• timepicker.getCurrentMinute()

Prof. Urmi Desai, SCET CO


List View
• Android ListView is a view which contains the group of items
and displays in a scrollable list. ListView is implemented by
importing android.widget.ListView class. ListView is a default
scrollable which does not use other scroll view.
• ListView uses Adapter classes which add the content from
data source (such as string array, array, database etc) to
ListView. Adapter bridges data between an AdapterViews and
other Views (ListView, ScrollView etc).

Prof. Urmi Desai, SCET CO


ArrayAdapter
Parameters Description

The current context. This value


context
can not be null.

The resource ID for the layout file


resource containing a layout to use when
instantiating views.

The id of the TextView within the


textViewResourceId
layout resource to be populated.

The objects to represent in the


objects ListView. This value cannot be
null.
Prof. Urmi Desai, SCET CO
listView=(ListView)findViewById(R.id.listView);
listItem = List View
getResources().getStringArray(R.array.array_technology);
final ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
listItem);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long l) {
// TODO Auto-generated method stub
String value=adapter.getItem(position);

Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHO
RT).show();
Prof. Urmi Desai, SCET CO
}
Strings.xml
<string-array name="array_technology">
<item>Android</item>
<item>Java</item>
<item>Php</item>
<item>Hadoop</item>
<item>Sap</item>
<item>Python</item>
<item>Ajax</item>
<item>C++</item>
<item>Ruby</item>
<item>Rails</item>
<item>.Net</item>
<item>Perl</item>
</string-array>
Prof. Urmi Desai, SCET CO
List View

Prof. Urmi Desai, SCET CO


Spinner View

Prof. Urmi Desai, SCET CO


Spinner View
• Android Spinner is like the combo box of AWT or
Swing. It can be used to display the multiple
options to the user in which only one item can be
selected by the user.
• Android spinner is like the drop down menu with
multiple values from which the end user can
select only one value.
• Android spinner is associated with AdapterView.
So you need to use one of the adapter classes
with spinner.
Prof. Urmi Desai, SCET CO
Spinner View
String[] country = { "India", "USA", "China", "Japan",
"Other"};
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the country list


ArrayAdapter aa = new
ArrayAdapter(this,android.R.layout.simple_spinner_item,c
ountry);
aa.setDropDownViewResource(android.R.layout.simple_spi
nner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
Prof. Urmi Desai, SCET CO
AutoCompleteTextView
• Android AutoCompleteTextView completes the word
based on the reserved words, so no need to write all
the characters of the word.
• Android AutoCompleteTextView is a editable text field,
it displays a list of suggestions in a drop down menu
from which user can select only one suggestion or
value.
• Android AutoCompleteTextView is the subclass of
EditText class. The MultiAutoCompleteTextView is the
subclass of AutoCompleteTextView class.
• using the ArrayAdapter class to display the array
content.

Prof. Urmi Desai, SCET CO


AutoCompleteTextView
String[] language
={"C","C++","Java",".NET","iPhone","Android","ASP.
NET","PHP"};
ArrayAdapter<String> adapter1 = new
ArrayAdapter<String>

(this,android.R.layout.select_dialog_item,language);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv =
(AutoCompleteTextView)findViewById(R.id.autoComplet
eTextView);
actv.setThreshold(1);//will start working from first
character
actv.setAdapter(adapter1);
Prof. Urmi Desai, SCET CO
AutoCompleteTextView

Prof. Urmi Desai, SCET CO


RatingBar
• Android RatingBar can be used to get the rating from the
user. The Rating returns a floating-point number. It may be
2.0, 3.5, 4.0 etc.
• Android RatingBar displays the rating in stars. Android
RatingBar is the subclass of AbsSeekBar class.
• The getRating() method of android RatingBar class returns the
rating number.

Prof. Urmi Desai, SCET CO


RatingBar

Prof. Urmi Desai, SCET CO


RatingBar

Prof. Urmi Desai, SCET CO


ProgressBar
• We can display the android progress bar dialog
box to display the status of work being done e.g.
downloading file, analyzing status of work etc.
• Here we are
using android.app.ProgressDialog class to show
the progress bar. Android ProgressDialog is the
subclass of AlertDialog class.
• The ProgressDialog class provides methods to
work on progress bar like setProgress(),
setMessage(), setProgressStyle(), setMax(),
show() etc. The progress range of Progress Dialog
is 0 to 100.
Prof. Urmi Desai, SCET CO
ProgressBar

Prof. Urmi Desai, SCET CO


Prof. Urmi Desai, SCET CO
Recycler View
• RecyclerView is an advanced and flexible version of
ListView and GridView.
• It is a container used for displaying large amount of data
sets that can be scrolled very efficiently by maintaining a
limited number of views.
• RecyclerView was introduced in Material Design in API
level 21 (Android 5.0 i.e Lollipop).
• Material Design brings lot of new features in Android
that changed a lot the visual design patterns regarding
the designing of modern Android applications.
• In RecyclerView android provides a lots of new features
which are not presentProf.inUrmi
existing
Desai, SCET COListView or GridView.
Recycler View

Prof. Urmi Desai, SCET CO


Recycler View

Prof. Urmi Desai, SCET CO


Card View
• CardView is another main element that can
represent the information in a card manner with
a drop shadow called elevation and corner radius
which looks consistent across the
platform. CardView was introduced in Material
Design in API level 21 (Android 5.0 i.e Lollipop).
• This new widget is a big step for displaying
data/information inside cards. We can easily
design good looking UI when we combined
CardView with RecyclerView. A CardView is a
ViewGroup that can be added in our Activity or
Fragment using a layout XML file.

Prof. Urmi Desai, SCET CO


Card View

Prof. Urmi Desai, SCET CO


Create Custom Layout in Android
• A ViewGroup in Android a special view that can
contain other Views.
• A ViewGroup can contain one or multiple child. All
other standard layout managers such as Linear
Layout, FrameLayout, RelativeLayout are
specialized sub classes of ViewGroup class that
layout their child in specific format.
• For example, LinearLayout layout its child one
adjacent to other either vertically or horizontally.
• Sometimes, due to the specific nature of the
requirement, the standard layout managers are not
enough. You need to extend the ViewGroup class to
create your own custom layout manager.
Prof. Urmi Desai, SCET CO
Create Custom Layout in Android
1.Extend your class from ViewGroup class.
2.You must override the onLayout() method. This method
is used to place child views.
3.Override onMeasure() method. The onMeasure()
method will be used to for parent to determine the size of
the view group based on calculating the child view size.
4.The onMeasure() and onLayout() method, will contain
the logic to organize the child views with in parent layout.
5. You can measure each of the child view height and
width by
calling getMeasuredWidth() and getMeasuredHeight()
methods.
Prof. Urmi Desai, SCET CO
Toolbar
• Toolbar was introduced in Material Design in API level 21
(Android 5.0 i.e Lollipop). Material Design brings lot of new
features in Android that changed a lot the visual design
patterns regarding the designing of modern Android
applications.
• Toolbar is a Viewgroup that can be placed at anywhere in the
Layout.

Prof. Urmi Desai, SCET CO


Elements of Toolbar In Android
• Navigation Button: It may be a Navigation menu toggle, up arrow, close,
done, collapse or any other glyph of the app’s choosing.
• Brand Logo Image: It may extend to the height of the toolbar and can be
arbitrarily wide.
• Title and SubTitle: A title should be a signpost for the current position of
Toolbar’s navigation hierarchy and the content contained there. Subtitle
represents any extended information about the current content. If an app
uses a logo then it should strongly consider omitting a title and subtitle.
• One or More Custom Views: An Application may add arbitrary child views
to the Toolbar. If child view’s Toolbar.LayoutParams indicates
CENTER_HORIZONTAL Gravity then view will attempt to center within the
available space remaining in the Toolbar after all other element’s have
been measured.
• Action Menu: The menu of Actions will pin to the end of the Toolbar
offering a few important, typical or frequent actions along with an
optional overflow menu for additional actions. Action buttons are aligned
vertically within the Toolbar’s minimum height if we set.

Prof. Urmi Desai, SCET CO


Android Menus
• Menu is a part of the user interface (UI) component which is used to
handle some common functionality around the application. By using
Menus in our applications, we can provide better and consistent user
experience throughout the application.
• Android provides a standard XML format to define menu items. Instead of
building a menu in our activity's code, we should define a menu and all its
items in an XML menu resource and load menu resource as a Menu object
in our activity or fragment.
Element Description
<menu> It’s a root element to define a Menu in XML file and it will hold one or more and
elements.
<item> It is used to create a menu item and it represents a single item on the menu. This
element may contain a nested <menu> element in order to create a submenu.
<group> It’s an optional and invisible for <item> elements. It is used to categorize the menu
items so they share properties such as active state and visibility.

Prof. Urmi Desai, SCET CO


Android Menus
• Android Different Types of Menus
• Options Menu:Options Menu is a primary collection of
menu items for an activity and it is useful to implement
actions that have a global impact on the app, such as
Settings, Search, etc.
• Context Menu: Context Menu is a floating menu that
appears when the user performs a long click on an element
and it is useful to implement actions that affect the
selected content or context frame.
• Popup Menu: Popup Menu displays a list of items in a
vertical list that’s anchored to the view that invoked the
menu and it’s useful for providing an overflow of actions
that related to specific content.

Prof. Urmi Desai, SCET CO


Options Menu
• By using Options Menu, we
can combine multiple actions
and other options that are
relevant to our
current activity. We can
define items for the options
menu from either
our Activity or Fragment class
.
• to define options menu, we
need to create a new
folder menu inside of our
project resource directory
(res/menu/) and add a new
XML (menu_example) file to
build the menu.

Prof. Urmi Desai, SCET CO


(options_menu.xml)
• <?xml version="1.0" encoding="utf-8"?>
• <menu
xmlns:android="http://schemas.android.com/apk/res/
android">
• <item android:id="@+id/fy_item"
• android:title="FY" />
• <item android:id="@+id/sy_item"
• android:title="SY" />
• <item android:id="@+id/ty_item"
• android:title="TY" />
• </menu>

Prof. Urmi Desai, SCET CO


• public class MainActivity extends AppCompatActivity {
• protected void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• setContentView(R.layout.activity_main);
• }
• public boolean onCreateOptionsMenu(Menu menu) {
• getMenuInflater().inflate(R.menu.options_menu, menu);
• return true;
• }
• public boolean onOptionsItemSelected(MenuItem item) {
• Toast.makeText(this, "Selected Item: " +item.getTitle(),
• Toast.LENGTH_SHORT).show();

Prof. Urmi Desai, SCET CO


• switch (item.getItemId()) {
• case R.id.fy_item:
• // do your code
• return true;
• case R.id.sy_item:
• // do your code
• return true;
• case R.id.ty_item:
• Intent i = new Intent(this, menu.class);
• startActivity(i);
• return true;
• default:
• return super.onOptionsItemSelected(item);
• }} }

Prof. Urmi Desai, SCET CO


Popup Menu
• The android Popup Menu provides an
overflow style menu for actions that are
related to specific content.

Prof. Urmi Desai, SCET CO


pop_menu.xml

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


<menu
xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/search_item" android:title="Search" />
<item android:id="@+id/upload_item" android:title="Upload" />
<item android:id="@+id/copy_item" android:title="Copy" />
<item android:id="@+id/print_item" android:title="Print" />
<item android:id="@+id/share_item" android:title="Share" />
<item android:id="@+id/bookmark_item" android:title="BookMark"
/>
</menu> Prof. Urmi Desai, SCET CO
• public class menu extends AppCompatActivity
implements PopupMenu.OnMenuItemClickListener {
@Override
• protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.pop_menu);
• Button btn = (Button) findViewById(R.id.CO);
btn.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
• PopupMenu popup = new PopupMenu(menu.this, v);
popup.setOnMenuItemClickListener(menu.this);
• popup.inflate(R.menu.popup_menu);
• popup.show();
• } }); }
Prof. Urmi Desai, SCET CO
• public boolean onMenuItemClick(MenuItem item) {
• Toast.makeText(this, "Selected Item: " +item.getTitle(),
Toast.LENGTH_SHORT).show();
• switch (item.getItemId())
• {
• case R.id.search_item: // do your code return true;
• case R.id.upload_item: // do your code return true;
• case R.id.copy_item: // do your code return true;
• case R.id.print_item: // do your code return true;
• case R.id.share_item: // do your code return true;
• case R.id.bookmark_item: // do your code return true;
• default: return false;
• }
• } Prof. Urmi Desai, SCET CO
Prof. Urmi Desai, SCET CO
Context Menu
• The android Context Menu
is more like the menu which
displayed on right-click in
Windows or Linux.
• The views which we used to
show the context menu on
long-press, we need to
register
that views using registerFor
ContextMenu(View) in
our activity and we need to
override onCreateContextM
enu() in
our activity or fragment.

Prof. Urmi Desai, SCET CO

You might also like