SlideShare une entreprise Scribd logo
1  sur  50
Télécharger pour lire hors ligne
Using Action Bar in Android: A Tutorial
http://eglobiotraining.com/
Prof. Erwin M. Globio, MSIT
Android Development Expert
http://eglobiotraining.com
Introduction to the ActionBar
What is the ActionBar
The ActionBar is located at the top of the activity. It can display
the activity title, icon, actions which can be triggered, additional
views Views other interactive items. It can also be used for
navigation in your application.
Older Android devices have a hardware Option button which
would open a menu at the bottom of the application once
pressed, i.e. the OptionsMenu. The ActionBar is superior to the
OptionsMenu, in that it is clearly visible, while the OptionsMenu
is only shown on request and the user may not recognize that
options are available.
http://eglobiotraining.com
Example
The following picture shows the ActionBar of a
The Google+ Android application with interactive
items and a navigation bar.
http://eglobiotraining.com
Using the ActionBar on older devices
The ActionBar has introduced in Android 3.0. The
ActionBar Sherlock library allows to use the ActionBar
on Android devices as of Android 1.6. You find this
library under the following link.
http://actionbarsherlock.com
http://eglobiotraining.com
Using the ActionBar
Creating actions in the ActionBar
An activity populates the ActionBar in its
onCreateOptionsMenu() method. We call these entries actions.
The actions for the ActionBar are typically defined in an XML
resource file. The MenuInflator class allows to inflate actions
defined in an XML file and add them to the ActionBar.
The showAsAction attribute allows you to define how the action
is displayed. For example the ifRoom attribute defines that the
action is on y displayed in the ActionBar if there is sufficient
space available.
http://eglobiotraining.com
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="@+id/action_refresh"
android:orderInCategory="100"
android:showAsAction="always"
android:icon="@drawable/ic_action_search"
android:title="Refresh"/>
<item
android:id="@+id/action_settings"
android:title="Settings">
</item>
</menu>
http://eglobiotraining.com
Search an actions in the ActionBar
To search for a menu item in a menu you can use the
findItem() method of the Menu class. This method allows to
search by id.
Reacting to actions selection
If an actions in the ActionBar is selected, the
onOptionsItemSelected() method is called. It receives the
selected action as parameter. Based on this information you
code can decide what to do.
http://eglobiotraining.com
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected",
Toast.LENGTH_SHORT)
.show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected",
Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
} http://eglobiotraining.com
Changing the menu
The onCreateOptionsMenu() method is only called once. If
you want to change the menu later you have to call the
invalidateOptionsMenu() method. Afterwards this
onCreateOptionsMenu() method is called again.
http://eglobiotraining.com
Customizing the ActionBar
Adjusting the ActionBar
You can change the visibility of the ActionBar at runtime. The
following code demonstrates that.
ActionBar actionBar = getActionBar();
actionBar.hide();
// More stuff here...
actionBar.show();
http://eglobiotraining.com
You can also change the text which is displayed
alongside the application icon at runtime. The
following example shows that.
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("mytest");
actionBar.setTitle(“eglobiotraining.com");
http://eglobiotraining.com
Assiging a Drawable
You also add a drawable to the ActionBar background via the
ActionBar.setBackgroundDrawable() method.
The ActionBar scales the image therefore it is best practice to
provide a scalable drawable, e.g. an 9-patch or XML drawable.
As of Android 4.2 the drawable for the ActionBar can also be an
animated.
http://eglobiotraining.com
Dimming the Android default navigation Buttons
You can also hide the software navigation button in your Android application
to have more space available. If the user touches the button of the screen the
navigation button are automatically shown again.
You can dim the navigation buttons in an activity with the following code.
getWindow().
getDecorView().
setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
http://eglobiotraining.com
The following screenshots show an application with and
without the navigation buttons.
http://eglobiotraining.com
Further options for the ActionBar
Using the home icon
The action bar shows an icon of your application, this is called the
home icon. You can add an action to this icon. If you select this
icon the onOptionsItemSelected() method will be called with the
value android.R.id.home. The recommendation is to return to the
main activity in your program.
// If home icon is clicked return to main Activity
case android.R.id.home:
Intent intent = new Intent(this, OverviewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
http://eglobiotraining.com
As of Android 4.1 this code is not required anymore, you can
simply set the parentActivityName in the AndroidManifest.xml
file, pointing to the parent activity.
<activity
android:name="com.vogella.android.actionbar.customviews.S
econdActivity"
android:label="@string/app_name"
android:parentActivityName="MainActivity">
</activity>
http://eglobiotraining.com
Navigation via the home icon
The home icon can also be used for an "up" navigation in your
application. In practice this is not frequently used by Android
applications and should therefore be avoided.
Enabling the split action bar
You can define that the action bar should be automatically split
by the system if not enough space is available.
You can activate that via the
android:uiOptions="SplitActionBarWhenNarrow" parameter in
the declaration of your application or activity in the
AndroidManifest.xml file.
http://eglobiotraining.com
Making the ActioinBar dynamic
Custom Views in the ActionBar
You can also add a custom View to the ActionBar. For this you use the setCustomView
method for the ActionView class. You also have to enable the display of custom views
via the setDisplayOptions() method by passing in the
ActionBar.DISPLAY_SHOW_CUSTOM flag.
For example you can define a layout file which contains a EditText element.
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/searchfield"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textFilter" >
</EditText>
This layout can be assigned to the ActionBar via the following code. The example
code allow attaches a listener to the custom view.
http://eglobiotraining.com
package com.vogella.android.actionbar.customviews;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// add the custom view to the action bar
actionBar.setCustomView(R.layout.actionbar_view);
EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
search.setOnEditorActionListener(new OnEditorActionListener() {
http://eglobiotraining.com
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
Toast.makeText(MainActivity.this, "Search triggered",
Toast.LENGTH_LONG).show();
return false;
}
});
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
}
}
http://eglobiotraining.com
Contextual ActionBar
A contextual action mode activates a temporary ActionBar that overlays the
application ActionBar for the duration of a particular sub-task.
The contextual action mode is typically activated by selecting an item or by
long clicking on it.
To implemented this, call the startActionMode() method on a View or on your
activity. This method gets an ActionMode.Callback object which is responsible
for the lifecycle of the contextual ActionBar.
You could also assign a context menu to a View via the
registerForContextMenu(view) method. A context menu is also activated if the
user "long presses" the view. The onCreateContextMenu() method is called
every time a context menu is activated as the context menu is discarded after
its usage. You should prefer the contextual action mode over the usage of
context menus.
http://eglobiotraining.com
Action view
An action view is a widget that appears in the action bar as a substitute
for an action item's button. You can for example use this feature to
replace an action item with a ProgressBar view. An action view for an
action can be defined via the android:actionLayout or
android:actionViewClass attribute to specify either a layout resource or
widget class to use.
This replacement is depicted in the following screenshots.
http://eglobiotraining.com
The following activity replace the icon at runtime with an action view which contains
a ProgressBar view.
package com.vogella.android.actionbar.progress;
import android.app.ActionBar;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
private MenuItem menuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
} http://eglobiotraining.com
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_load:
menuItem = item;
menuItem.setActionView(R.layout.progressbar);
menuItem.expandActionView();
TestTask task = new TestTask();
task.execute("test");
break;
default:
break;
}
return true;
}
http://eglobiotraining.com
private class TestTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// Simulate something long running
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
menuItem.collapseActionView();
menuItem.setActionView(null);
}
};
}
http://eglobiotraining.com
The following code shows the layout used for the action view.
<?xml version="1.0" encoding="utf-8"?>
<ProgressBar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progressBar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ProgressBar>
http://eglobiotraining.com
The following code shows the XML files for the menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="always"
android:title="Settings"
/>
<item
android:id="@+id/menu_load"
android:icon="@drawable/navigation_refresh"
android:orderInCategory="200"
android:showAsAction="always"
android:title="Load"/>
</menu>
http://eglobiotraining.com
ActionProvider
Overview of ActionProvider
An ActionProvider defines rich menu interaction in a single
component. It can generate action views for use in the
action bar, dynamically populate submenus of a action item,
and handle default action item invocations.
Currently the Android platform provides two ActionProvider
the MediaRouteActionProvider and the
ShareActionProvider.
http://eglobiotraining.com
Example: usage of the ShareActionProvider
The following uses the ShareActionProvider to demonstrate
the usage of ActionProviders.
This ActionProvider allows you to use share selected content
using application which have registered the
Intent.ACTION_SEND intent.
To use ShareActionProvider you have to define a special
menu entry for it and assign an intent which contain the
sharing data to it.
http://eglobiotraining.com
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_share"
android:title="Share"
android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvid
er" />
<item
android:id="@+id/item1"
android:showAsAction="ifRoom"
android:title="More entries...">
</item>
</menu>
http://eglobiotraining.com
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
// Get the ActionProvider
provider = (ShareActionProvider)
menu.findItem(R.id.menu_share)
.getActionProvider();
// Initialize the share intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
provider.setShareIntent(intent);
return true;
}
http://eglobiotraining.com
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.menu_share:
doShare();
break;
default:
break;
}
return true;
}
http://eglobiotraining.com
public void doShare() {
// Populare the share intent with data
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "This is a message
for you");
provider.setShareIntent(intent);
}
http://eglobiotraining.com
Navigation with the ActionBar
Tab navigation
Fragments can also be used in combination with the
ActionBar for navigation. For this your main activity needs
to implement a TabListener which is responsible for
moving between the tabs.
The ActionBar allows to add tabs to it via the newTab()
method.
The following code shows such an activity. It uses dummy
activities to demonstrate the switch.
http://eglobiotraining.com
package com.vogella.android.actionbar.tabs;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
http://eglobiotraining.com
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current tab position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM =
"selected_navigation_item";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
http://eglobiotraining.com
// Set up the action bar to show tabs.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText(R.string.title_section1)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section2)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section3)
.setTabListener(this));
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTE
D_NAVIGATION_ITEM));
}
}
http://eglobiotraining.com
@Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
getActionBar()
.getSelectedNavigationIndex());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
http://eglobiotraining.com
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the
// container view.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,
tab.getPosition() + 1);
fragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
http://eglobiotraining.com
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A dummy fragment representing a section of the app
*/
http://eglobiotraining.com
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER =
"placeholder_text";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(ARG_SEC
TION_NUMBER)));
return textView;
}
}
}
http://eglobiotraining.com
Dropdown menu navigation
You can also use a spinner in the action bar for navigation. The
following code demonstrates that.
package com.vogella.android.actionbar.spinner;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
http://eglobiotraining.com
public class MainActivity extends FragmentActivity
implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key
representing the
* current dropdown position.
*/
private static final String
STATE_SELECTED_NAVIGATION_ITEM =
"selected_navigation_item";
http://eglobiotraining.com
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
final String[] dropdownValues =
getResources().getStringArray(R.array.dropdown);
// Specify a SpinnerAdapter to populate the dropdown list.
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(actionBar.getThemedContext(),
http://eglobiotraining.com
android.R.layout.simple_spinner_item, android.R.id.text1,
dropdownValues);
adapter.setDropDownViewResource(android.R.layout.simple_
spinner_dropdown_item);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(adapter, this);
// Use getActionBar().getThemedContext() to ensure
// that the text color is always appropriate for the action
bar
// background rather than the activity background.
}
http://eglobiotraining.com
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
{
getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_
SELECTED_NAVIGATION_ITEM));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
http://eglobiotraining.com
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
return true;
}
http://eglobiotraining.com
/**
* A dummy fragment
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "placeholder_text";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
}
http://eglobiotraining.com
http://eglobiotraining.com
Prof. Erwin M. Globio, MSIT
Managing Director of eglobiotraining.com
Senior IT Professor of Far Eastern University
Mobile: 09393741359 | 09323956678
Landline: (02) 428-7127
Email: erwin_globio@yahoo.com
Skype: erwinglobio
Website: http://eglobiotraining.com/
http://eglobiotraining.com

Contenu connexe

Tendances (20)

JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
4.C#
4.C#4.C#
4.C#
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
 
Activity lifecycle
Activity lifecycleActivity lifecycle
Activity lifecycle
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
 
Android styles and themes
Android styles and themesAndroid styles and themes
Android styles and themes
 
Android Services
Android ServicesAndroid Services
Android Services
 
Servlets
ServletsServlets
Servlets
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Css pseudo-classes
Css pseudo-classesCss pseudo-classes
Css pseudo-classes
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 

En vedette

Menu in android
Menu in androidMenu in android
Menu in androidDurai S
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfacesC.o. Nieto
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding MenuKan-Han (John) Lu
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Nehil Jain
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application DevelopmentRamesh Prasad
 

En vedette (10)

Menu in android
Menu in androidMenu in android
Menu in android
 
android menus
android menusandroid menus
android menus
 
Android ui menu
Android ui menuAndroid ui menu
Android ui menu
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfaces
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding Menu
 
Android in practice
Android in practiceAndroid in practice
Android in practice
 
Action Bar and Menu
Action Bar and MenuAction Bar and Menu
Action Bar and Menu
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 

Similaire à Action Bar in Android

Create an other activity lesson 3
Create an other activity lesson 3Create an other activity lesson 3
Create an other activity lesson 3Kalluri Vinay Reddy
 
Android TV: Building apps with Google’s Leanback Library
Android TV: Building apps with  Google’s Leanback LibraryAndroid TV: Building apps with  Google’s Leanback Library
Android TV: Building apps with Google’s Leanback LibraryJoe Birch
 
Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interactionEdi Faizal
 
What's New in Android
What's New in AndroidWhat's New in Android
What's New in AndroidRobert Cooper
 
Android Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and IntentAndroid Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and Intentadmin220812
 
Android App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAndroid App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAnuchit Chalothorn
 
Handling action bar in Android
Handling action bar in AndroidHandling action bar in Android
Handling action bar in Androidindiangarg
 
Android Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatAndroid Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatcbeyls
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivitiesmaamir farooq
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activitiesmaamir farooq
 
Advancing the UI — Part 1: Look, Motion, and Gestures
Advancing the UI — Part 1: Look, Motion, and GesturesAdvancing the UI — Part 1: Look, Motion, and Gestures
Advancing the UI — Part 1: Look, Motion, and GesturesSamsung Developers
 

Similaire à Action Bar in Android (20)

Android action bar and notifications-chapter16
Android action bar and notifications-chapter16Android action bar and notifications-chapter16
Android action bar and notifications-chapter16
 
Android 3
Android 3Android 3
Android 3
 
Lesson 9
Lesson 9Lesson 9
Lesson 9
 
Create an other activity lesson 3
Create an other activity lesson 3Create an other activity lesson 3
Create an other activity lesson 3
 
Android TV: Building apps with Google’s Leanback Library
Android TV: Building apps with  Google’s Leanback LibraryAndroid TV: Building apps with  Google’s Leanback Library
Android TV: Building apps with Google’s Leanback Library
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interaction
 
Android session 3
Android session 3Android session 3
Android session 3
 
What's New in Android
What's New in AndroidWhat's New in Android
What's New in Android
 
Action bar
Action barAction bar
Action bar
 
Android Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and IntentAndroid Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and Intent
 
Android App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UIAndroid App Development 03 : Widget &amp; UI
Android App Development 03 : Widget &amp; UI
 
Handling action bar in Android
Handling action bar in AndroidHandling action bar in Android
Handling action bar in Android
 
Activity & Shared Preference
Activity & Shared PreferenceActivity & Shared Preference
Activity & Shared Preference
 
Exercises
ExercisesExercises
Exercises
 
Android Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatAndroid Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompat
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activities
 
Advancing the UI — Part 1: Look, Motion, and Gestures
Advancing the UI — Part 1: Look, Motion, and GesturesAdvancing the UI — Part 1: Look, Motion, and Gestures
Advancing the UI — Part 1: Look, Motion, and Gestures
 
Android
AndroidAndroid
Android
 

Plus de Prof. Erwin Globio

Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic ConfigurationProf. Erwin Globio
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps DevelopmentProf. Erwin Globio
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development LatestProf. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)Prof. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)Prof. Erwin Globio
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer ProgrammingProf. Erwin Globio
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android ProblemsProf. Erwin Globio
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and InstallationProf. Erwin Globio
 

Plus de Prof. Erwin Globio (20)

Embedded System Presentation
Embedded System PresentationEmbedded System Presentation
Embedded System Presentation
 
BSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis GuidelinesBSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis Guidelines
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Networking Trends
Networking TrendsNetworking Trends
Networking Trends
 
Sq lite presentation
Sq lite presentationSq lite presentation
Sq lite presentation
 
Ethics for IT Professionals
Ethics for IT ProfessionalsEthics for IT Professionals
Ethics for IT Professionals
 
Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic Configuration
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps Development
 
Cloud Computing Latest
Cloud Computing LatestCloud Computing Latest
Cloud Computing Latest
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
 
iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)
 
iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
Android Fragments
Android FragmentsAndroid Fragments
Android Fragments
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android Problems
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and Installation
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Resource Speaker
Resource SpeakerResource Speaker
Resource Speaker
 

Dernier

Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?TechSoup
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 

Dernier (20)

Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
Finals of Kant get Marx 2.0 : a general politics quiz
Finals of Kant get Marx 2.0 : a general politics quizFinals of Kant get Marx 2.0 : a general politics quiz
Finals of Kant get Marx 2.0 : a general politics quiz
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 

Action Bar in Android

  • 1. Using Action Bar in Android: A Tutorial http://eglobiotraining.com/ Prof. Erwin M. Globio, MSIT Android Development Expert http://eglobiotraining.com
  • 2. Introduction to the ActionBar What is the ActionBar The ActionBar is located at the top of the activity. It can display the activity title, icon, actions which can be triggered, additional views Views other interactive items. It can also be used for navigation in your application. Older Android devices have a hardware Option button which would open a menu at the bottom of the application once pressed, i.e. the OptionsMenu. The ActionBar is superior to the OptionsMenu, in that it is clearly visible, while the OptionsMenu is only shown on request and the user may not recognize that options are available. http://eglobiotraining.com
  • 3. Example The following picture shows the ActionBar of a The Google+ Android application with interactive items and a navigation bar. http://eglobiotraining.com
  • 4. Using the ActionBar on older devices The ActionBar has introduced in Android 3.0. The ActionBar Sherlock library allows to use the ActionBar on Android devices as of Android 1.6. You find this library under the following link. http://actionbarsherlock.com http://eglobiotraining.com
  • 5. Using the ActionBar Creating actions in the ActionBar An activity populates the ActionBar in its onCreateOptionsMenu() method. We call these entries actions. The actions for the ActionBar are typically defined in an XML resource file. The MenuInflator class allows to inflate actions defined in an XML file and add them to the ActionBar. The showAsAction attribute allows you to define how the action is displayed. For example the ifRoom attribute defines that the action is on y displayed in the ActionBar if there is sufficient space available. http://eglobiotraining.com
  • 7. Search an actions in the ActionBar To search for a menu item in a menu you can use the findItem() method of the Menu class. This method allows to search by id. Reacting to actions selection If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do. http://eglobiotraining.com
  • 8. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuitem1: Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT) .show(); break; case R.id.menuitem2: Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT) .show(); break; default: break; } return true; } http://eglobiotraining.com
  • 9. Changing the menu The onCreateOptionsMenu() method is only called once. If you want to change the menu later you have to call the invalidateOptionsMenu() method. Afterwards this onCreateOptionsMenu() method is called again. http://eglobiotraining.com
  • 10. Customizing the ActionBar Adjusting the ActionBar You can change the visibility of the ActionBar at runtime. The following code demonstrates that. ActionBar actionBar = getActionBar(); actionBar.hide(); // More stuff here... actionBar.show(); http://eglobiotraining.com
  • 11. You can also change the text which is displayed alongside the application icon at runtime. The following example shows that. ActionBar actionBar = getActionBar(); actionBar.setSubtitle("mytest"); actionBar.setTitle(“eglobiotraining.com"); http://eglobiotraining.com
  • 12. Assiging a Drawable You also add a drawable to the ActionBar background via the ActionBar.setBackgroundDrawable() method. The ActionBar scales the image therefore it is best practice to provide a scalable drawable, e.g. an 9-patch or XML drawable. As of Android 4.2 the drawable for the ActionBar can also be an animated. http://eglobiotraining.com
  • 13. Dimming the Android default navigation Buttons You can also hide the software navigation button in your Android application to have more space available. If the user touches the button of the screen the navigation button are automatically shown again. You can dim the navigation buttons in an activity with the following code. getWindow(). getDecorView(). setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); http://eglobiotraining.com
  • 14. The following screenshots show an application with and without the navigation buttons. http://eglobiotraining.com
  • 15. Further options for the ActionBar Using the home icon The action bar shows an icon of your application, this is called the home icon. You can add an action to this icon. If you select this icon the onOptionsItemSelected() method will be called with the value android.R.id.home. The recommendation is to return to the main activity in your program. // If home icon is clicked return to main Activity case android.R.id.home: Intent intent = new Intent(this, OverviewActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; http://eglobiotraining.com
  • 16. As of Android 4.1 this code is not required anymore, you can simply set the parentActivityName in the AndroidManifest.xml file, pointing to the parent activity. <activity android:name="com.vogella.android.actionbar.customviews.S econdActivity" android:label="@string/app_name" android:parentActivityName="MainActivity"> </activity> http://eglobiotraining.com
  • 17. Navigation via the home icon The home icon can also be used for an "up" navigation in your application. In practice this is not frequently used by Android applications and should therefore be avoided. Enabling the split action bar You can define that the action bar should be automatically split by the system if not enough space is available. You can activate that via the android:uiOptions="SplitActionBarWhenNarrow" parameter in the declaration of your application or activity in the AndroidManifest.xml file. http://eglobiotraining.com
  • 18. Making the ActioinBar dynamic Custom Views in the ActionBar You can also add a custom View to the ActionBar. For this you use the setCustomView method for the ActionView class. You also have to enable the display of custom views via the setDisplayOptions() method by passing in the ActionBar.DISPLAY_SHOW_CUSTOM flag. For example you can define a layout file which contains a EditText element. <?xml version="1.0" encoding="utf-8"?> <EditText xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/searchfield" android:layout_width="match_parent" android:layout_height="match_parent" android:inputType="textFilter" > </EditText> This layout can be assigned to the ActionBar via the following code. The example code allow attaches a listener to the custom view. http://eglobiotraining.com
  • 19. package com.vogella.android.actionbar.customviews; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getActionBar(); // add the custom view to the action bar actionBar.setCustomView(R.layout.actionbar_view); EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield); search.setOnEditorActionListener(new OnEditorActionListener() { http://eglobiotraining.com
  • 20. @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Toast.makeText(MainActivity.this, "Search triggered", Toast.LENGTH_LONG).show(); return false; } }); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME); } } http://eglobiotraining.com
  • 21. Contextual ActionBar A contextual action mode activates a temporary ActionBar that overlays the application ActionBar for the duration of a particular sub-task. The contextual action mode is typically activated by selecting an item or by long clicking on it. To implemented this, call the startActionMode() method on a View or on your activity. This method gets an ActionMode.Callback object which is responsible for the lifecycle of the contextual ActionBar. You could also assign a context menu to a View via the registerForContextMenu(view) method. A context menu is also activated if the user "long presses" the view. The onCreateContextMenu() method is called every time a context menu is activated as the context menu is discarded after its usage. You should prefer the contextual action mode over the usage of context menus. http://eglobiotraining.com
  • 22. Action view An action view is a widget that appears in the action bar as a substitute for an action item's button. You can for example use this feature to replace an action item with a ProgressBar view. An action view for an action can be defined via the android:actionLayout or android:actionViewClass attribute to specify either a layout resource or widget class to use. This replacement is depicted in the following screenshots. http://eglobiotraining.com
  • 23. The following activity replace the icon at runtime with an action view which contains a ProgressBar view. package com.vogella.android.actionbar.progress; import android.app.ActionBar; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends Activity { private MenuItem menuItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM); } http://eglobiotraining.com
  • 24. @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_load: menuItem = item; menuItem.setActionView(R.layout.progressbar); menuItem.expandActionView(); TestTask task = new TestTask(); task.execute("test"); break; default: break; } return true; } http://eglobiotraining.com
  • 25. private class TestTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { // Simulate something long running try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { menuItem.collapseActionView(); menuItem.setActionView(null); } }; } http://eglobiotraining.com
  • 26. The following code shows the layout used for the action view. <?xml version="1.0" encoding="utf-8"?> <ProgressBar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/progressBar2" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ProgressBar> http://eglobiotraining.com
  • 27. The following code shows the XML files for the menu. <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_settings" android:orderInCategory="100" android:showAsAction="always" android:title="Settings" /> <item android:id="@+id/menu_load" android:icon="@drawable/navigation_refresh" android:orderInCategory="200" android:showAsAction="always" android:title="Load"/> </menu> http://eglobiotraining.com
  • 28. ActionProvider Overview of ActionProvider An ActionProvider defines rich menu interaction in a single component. It can generate action views for use in the action bar, dynamically populate submenus of a action item, and handle default action item invocations. Currently the Android platform provides two ActionProvider the MediaRouteActionProvider and the ShareActionProvider. http://eglobiotraining.com
  • 29. Example: usage of the ShareActionProvider The following uses the ShareActionProvider to demonstrate the usage of ActionProviders. This ActionProvider allows you to use share selected content using application which have registered the Intent.ACTION_SEND intent. To use ShareActionProvider you have to define a special menu entry for it and assign an intent which contain the sharing data to it. http://eglobiotraining.com
  • 30. <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_share" android:title="Share" android:showAsAction="ifRoom" android:actionProviderClass="android.widget.ShareActionProvid er" /> <item android:id="@+id/item1" android:showAsAction="ifRoom" android:title="More entries..."> </item> </menu> http://eglobiotraining.com
  • 31. @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); // Get the ActionProvider provider = (ShareActionProvider) menu.findItem(R.id.menu_share) .getActionProvider(); // Initialize the share intent Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); provider.setShareIntent(intent); return true; } http://eglobiotraining.com
  • 32. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_share: doShare(); break; default: break; } return true; } http://eglobiotraining.com
  • 33. public void doShare() { // Populare the share intent with data Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, "This is a message for you"); provider.setShareIntent(intent); } http://eglobiotraining.com
  • 34. Navigation with the ActionBar Tab navigation Fragments can also be used in combination with the ActionBar for navigation. For this your main activity needs to implement a TabListener which is responsible for moving between the tabs. The ActionBar allows to add tabs to it via the newTab() method. The following code shows such an activity. It uses dummy activities to demonstrate the switch. http://eglobiotraining.com
  • 35. package com.vogella.android.actionbar.tabs; import android.app.ActionBar; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; http://eglobiotraining.com
  • 36. public class MainActivity extends FragmentActivity implements ActionBar.TabListener { /** * The serialization (saved instance state) Bundle key representing the * current tab position. */ private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); http://eglobiotraining.com
  • 37. // Set up the action bar to show tabs. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // For each of the sections in the app, add a tab to the action bar. actionBar.addTab(actionBar.newTab().setText(R.string.title_section1) .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText(R.string.title_section2) .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText(R.string.title_section3) .setTabListener(this)); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore the previously serialized current tab position. if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) { getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTE D_NAVIGATION_ITEM)); } } http://eglobiotraining.com
  • 38. @Override public void onSaveInstanceState(Bundle outState) { // Serialize the current tab position. outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar() .getSelectedNavigationIndex()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } http://eglobiotraining.com
  • 39. @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, show the tab contents in the // container view. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1); fragment.setArguments(args); getFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } http://eglobiotraining.com
  • 40. @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A dummy fragment representing a section of the app */ http://eglobiotraining.com
  • 41. public static class DummySectionFragment extends Fragment { public static final String ARG_SECTION_NUMBER = "placeholder_text"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setGravity(Gravity.CENTER); textView.setText(Integer.toString(getArguments().getInt(ARG_SEC TION_NUMBER))); return textView; } } } http://eglobiotraining.com
  • 42. Dropdown menu navigation You can also use a spinner in the action bar for navigation. The following code demonstrates that. package com.vogella.android.actionbar.spinner; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; http://eglobiotraining.com
  • 43. public class MainActivity extends FragmentActivity implements ActionBar.OnNavigationListener { /** * The serialization (saved instance state) Bundle key representing the * current dropdown position. */ private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item"; http://eglobiotraining.com
  • 44. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar to show a dropdown list. final ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); final String[] dropdownValues = getResources().getStringArray(R.array.dropdown); // Specify a SpinnerAdapter to populate the dropdown list. ArrayAdapter<String> adapter = new ArrayAdapter<String>(actionBar.getThemedContext(), http://eglobiotraining.com
  • 45. android.R.layout.simple_spinner_item, android.R.id.text1, dropdownValues); adapter.setDropDownViewResource(android.R.layout.simple_ spinner_dropdown_item); // Set up the dropdown list navigation in the action bar. actionBar.setListNavigationCallbacks(adapter, this); // Use getActionBar().getThemedContext() to ensure // that the text color is always appropriate for the action bar // background rather than the activity background. } http://eglobiotraining.com
  • 46. @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore the previously serialized current dropdown position. if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) { getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_ SELECTED_NAVIGATION_ITEM)); } } @Override public void onSaveInstanceState(Bundle outState) { // Serialize the current dropdown position. outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar() .getSelectedNavigationIndex()); } http://eglobiotraining.com
  • 47. @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onNavigationItemSelected(int position, long id) { // When the given dropdown item is selected, show its contents in the // container view. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); getFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); return true; } http://eglobiotraining.com
  • 48. /** * A dummy fragment */ public static class DummySectionFragment extends Fragment { public static final String ARG_SECTION_NUMBER = "placeholder_text"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setGravity(Gravity.CENTER); textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))); return textView; } } } http://eglobiotraining.com
  • 50. Prof. Erwin M. Globio, MSIT Managing Director of eglobiotraining.com Senior IT Professor of Far Eastern University Mobile: 09393741359 | 09323956678 Landline: (02) 428-7127 Email: erwin_globio@yahoo.com Skype: erwinglobio Website: http://eglobiotraining.com/ http://eglobiotraining.com