SlideShare a Scribd company logo
1 of 41
1
A Programme Under the Compumitra Series
Copyright 2014 © Sunmitra Education Technologies Limited, India
Handling Action Bar
The action bar is a window feature that
identifies the user location, and provides
user actions and navigation modes.
2
OUTLINE
CREATE A NEW ANDROID PROJECT TO
UNDERSTAND THE ACTION BAR
CREATING A ACTION BAR STRUCTURE.
MAKING THE ACTION BAR WORK
CODE EXPLANATION
MODIFICATION AND ERROR TRIALS
HOME EXERCISE.
SUMMARY
3
Create A New Android
Project to understand the
Action Bar Making.
4
Create New Android Project with
1) Application Name: HandlingActionBar
2) Project Name: HandlingActionBar
3) Package Name:
com.company.handlingactionbar
4) Set Minimum Required SDK: API 8
5) Target SDK: API 19
6) Compile With: API 19
7) Theme: Holo Light with…
8) Activity Name: MainActivity
9) And Navigation Type: None
CREATE NEW APPLICATION
5
CREATING A ACTION BAR
STRUCTURE.
To create a menu structure which appears
on clicking the menu button on your
emulator.
6
<item android:id="@+id/action_google"
android:title="@string/google"
android:orderInCategory="100"
app:showAsAction="never" />
<item android:id="@+id/action_yahoo"
android:title="@string/yahoo"
android:orderInCategory="101"
app:showAsAction="never" />
MODIFICATION IN MENUMAIN.XML FILE
 Go to HandlingActionBar->res->menu->main.xml file (XML view).
1) Remove pre-written <item android:id
....... ="never"/> code.
2) Add this code with in <menu>
element of main.xml file.
7
<string name="google">Google</string>
<string name="yahoo">Yahoo</string>
<string name="hello_world">Select any option from Action Bar</string>
EDITING STRINGS.XML FILE
1. Go to HandlingActionBar ->res->values->strings.xml file.
2. Click on strings.xml (XML view ).
1) Change value of string
app_name to Action Bar
2) Change value of string
hello_world to Select any
option from Action Bar
3)Add these codes in strings.xml
8
MAKING THE ACTION BAR
WORK
To make the items defined in a action bar
to operate their respective functions.
9
fragment1.xml
CREATE NEW RESOURCE FILE: fragment1.xml-1
1. Go to HandlingActionBar ->res->layout.
2. Right click on layout.
3. Select New->File (from the drop down list).
1.A new dialog box appears.
Type fragment1.xml in
File_name and click on Finish.
10
CREATE NEW RESOURCE FILE: fragment1.xml-2
1.Copy all code from fragment_main.xml
and Paste it in fragment1.xml
11
EDITING RESOURCE FILE: fragment1.xml -1
1. Go to HandlingActionBar->res->layout->fragment1.xml file.
2. Click on the Graphical Layout.
3.Delete the default TextView
1.Select the given TextView
and press delete.
12
EDITING RESOURCE FILE: fragment1.xml -2
Go to Pallete and drag and drop
WebView widget from Composite.
13
android:id="@+id/webView_google"
EDITING RESOURCE FILE: fragment1.xml -3
1) Go to fragment1.xml (XML view) file.
2) add android:id="@+id/fragment1" in Layout (if
already given, change it to fragment1 )
4) and change ID to
android:id="@+id/webView_google" in WebView
14
CREATE NEW RESOURCE FILE: fragment2.xml-1
1. Go to HandlingActionBar ->res->layout.
2. Right click on layout.
3. Select New->File (from the drop down list).
1.A new dialog box appears.
Type fragment2.xml in
File_name and click on Finish.
15
CREATE NEW RESOURCE FILE: fragment2.xml-2
Copy all code from fragment1.xml and Paste it in fragment2.xml
2) Change its ID to
android:id="@+id/fragment2"
in Layout
3) and change ID of WebView to
android:id="@+id/webView_yahoo"
16
android:id="@+id/fragment_main "
EDITING RESOURCE FILE: fragment_main.xml
1) Go to fragment_main.xml (XML view) file.
2) add android:id="@+id/
fragment_main " in Layout (if already
given, change it to fragment_main)
17
public static class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
}
public static class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2, container, false);
return rootView;
}
}
JAVA CODE-1
Add this code after the PlaceholderFragment
class to create 2 Fragment classes.
Go to HandlingActionBar->src-><Package Name>-> MainActivity.java file
18
JAVA CODE-2
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment2()).commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment1()).commit();
2. Add this code before the pre-written
lines in if statement of onCreate method of
MainActivity class.
pre-written lines in if statement of onCreate method.
1. Import android.webkit.WebView; ,
android.webkit.WebViewClient;,
android.widget.RelativeLayout;.
19
JAVA CODE-3
Now delete the highlighted code (which showing error because we have removed
action-settings menu item from menu>main.xml file) from onOptionsItemSelected
method of MainActivity class.
20
RelativeLayout layoutmain=(RelativeLayout) findViewById(R.id.fragment_main);
RelativeLayout layoutf1 = (RelativeLayout) findViewById(R.id.fragment1);
RelativeLayout layoutf2 = (RelativeLayout) findViewById(R.id.fragment2);
layoutmain.setVisibility(View.GONE);
if (id == R.id.action_google) {
layoutf2.setVisibility(View.GONE);
layoutf1.setVisibility(View.VISIBLE);
WebView webview=(WebView)findViewById(R.id.webView_google);
webview.loadUrl("http://www.google.co.in");
webview.setWebViewClient(new WebViewClient());
webview.setHorizontalScrollBarEnabled(false);
return true;
}
else if(id == R.id.action_yahoo) {
layoutf2.setVisibility(View.VISIBLE);
layoutf1.setVisibility(View.GONE);
WebView webview=(WebView)findViewById(R.id.webView_yahoo);
webview.loadUrl("http://www.yahoo.com");
webview.setWebViewClient(new WebViewClient());
webview.setHorizontalScrollBarEnabled(false);
return true;
}
JAVA CODE-4
Type this code in
onOptionsItemSelected method
just before the return statement.
21
JAVA CODE-5
1. Typed code before
return statement
2. return statement
22
EDIT MANIFEST.XML FILE-1
1. Go to HandlingActionBar -> AndroidManifest.xml file.
2. Click on the Permissions.
3. Now click on Add Button.
23
EDIT MANIFEST.XML FILE-2
1. A new dialog box appears.
Now select Uses Permission
and click on OK.
2. Now write
android.permission.INTERNET in the
Name or you can also select from the
drop down window.
24
RUNNING THE APPLICATION ON EMULATOR-1
Run your application on your emulator.
2. Select any one from
the given options.
1. Click on default Action bar icon
to open Action bar sub menu.
25
RUNNING THE APPLICATION ON EMULATOR-2
Similarly when you will select
Google, Google page in WebView of
Fragment1 will be displayed on your
emulator screen.
1.Select Yahoo, and wait to load page.
your emulator screen will display
Yahoo page in WebView of
Fragment2.
26
CODE EXPLANATION
27
CODE EXPLANATION: menu->main.xml
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.company.handlingactionbar.MainActivity" >
<item android:id="@+id/action_google"
android:title="@string/google"
android:orderInCategory="100"
app:showAsAction="never" />
<item android:id="@+id/action_yahoo"
android:title="@string/yahoo"
android:orderInCategory="101"
app:showAsAction="never" />
</menu>
The first attribute ID allows the item
tag to be given a name and
referenced in your Java code.
Title attribute id is the title or
label for the menu button.
Menu tag is used
to use menu.
This keyword Defines, When and
how this item should appear as an
action item in the Action Bar.
28
CODE EXPLANATION: MainActivity.java-1
public static class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView =
inflater.inflate(R.layout.fragment1, container,
false);
return rootView;
}
}
public static class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView =
inflater.inflate(R.layout.fragment2, container,
false);
return rootView;
}
} Here we creates 2 classes Fragment1 and Fragment2 for
fragment1 and fragment2 layout.
29
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment1()).commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment2()).commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new
PlaceholderFragment()).commit();
}
} These lines adds Fragment1, Fragment2,
PlaceholderFragment to MainActivity.
CODE EXPLANATION: MainActivity.java-2
30
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Inflate the menu; this adds items to the action bar if it is
present.
Uses the inflate( ) method and the R.menu.main path to
our mein.xml file.
The R equates to the res folder of our
project.
CODE EXPLANATION: MainActivity.java-3
31
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
RelativeLayout layoutmain=(RelativeLayout)
findViewById(R.id.fragment_main);
RelativeLayout layoutf1 = (RelativeLayout)
findViewById(R.id.fragment1);
RelativeLayout layoutf2 = (RelativeLayout)
findViewById(R.id.fragment2);
layoutmain.setVisibility(View.GONE);
if (id == R.id.action_google) {
layoutf2.setVisibility(View.GONE);
layoutf1.setVisibility(View.VISIBLE);
CODE EXPLANATION: MainActivity.java-4
Gets the selected Action
Bar item ID.
This method is called on
selection of menu item.
Creates the objects of
fragment_main,
fragment1 and
fragment2 layout types.
Sets the visibility of
layoutmain to hidden
Sets the visibility of layoutf1 (fragment1) and
Checks, whether selected
item ID matches with given
item ID or not.
32
WebView
webview=(WebView)findViewById(R.id.webView_google);
webview.loadUrl("http://www.google.co.in");
webview.setWebViewClient(new WebViewClient());
webview.setHorizontalScrollBarEnabled(false);
return true;
}
else if(id == R.id.action_yahoo) {
layoutf2.setVisibility(View.VISIBLE);
layoutf1.setVisibility(View.GONE);
WebView
webview=(WebView)findViewById(R.id.webView_yahoo);
webview.loadUrl("http://www.yahoo.com");
webview.setWebViewClient(new WebViewClient());
webview.setHorizontalScrollBarEnabled(false);
return true;
}
return super.onOptionsItemSelected(item);
}
Creates the object
of webview and
sets its URL.
CODE EXPLANATION: MainActivity.java-5
Checks, whether selected
item ID matches with given
item ID or not.
33
MODIFICATION AND ERROR
TRIALS
34
android:icon="@drawable/google "
app:showAsAction="ifRoom" />
android:icon="@drawable/yahoo "
app:showAsAction="ifRoom" />
MODIFICATION TRIAL-1
1) Add attribute
android:icon="@drawable/
google" in action_google
item
1. Go to HandlingActionBar->res->menu->main.xml file (XML view).
3) Add Change attribute value
of app:showAsAction to
"ifRoom" from both items.
2) Add attribute android:icon="@drawable/yahoo" in action_google item
Note: If Minimum Required SDK of your app is Android 3.0 and Above (If your
app is not using the Support Library for compatibility) then use
android:showAsAction instead of app:showAsAction
35
MODIFICATION TRIAL-2
1. Copy 2 images from http://sunmitra.com/cm-
android/actionbar/google.png
and http://sunmitra.com/cm-android/actionbar/yahoo.png
Samples
1- google.png
2-yahoo.png
Pasted files.
3) And paste both images
in all drawable folders.
36
RUNNING THE APPLICATION ON EMULATOR-1
Watch the affect on Action
Bar items position.
Run your application on your emulator .
37
ERROR TRIALS-1
Go to HandlingActionBar->src-><Package Name>-> MainActivity.java file
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment2()).commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment1()).commit();
Pre-written lines.
Remove these lines from onCreate
method of MainActivity class and
write again after the pre-written lines.
RUN project and watch the affects.
38
else if(id == R.id.action_yahoo) {
layoutf2.setVisibility(View.VISIBLE);
layoutf1.setVisibility(View.GONE);
WebView webview=(WebView)findViewById(R.id.webView_yahoo);
webview.loadUrl("http://www.yahoo.com");
webview.setWebViewClient(new WebViewClient());
webview.setHorizontalScrollBarEnabled(false);
return true;
}
ERROR TRIALS-2
Go to HandlingActionBar->src-><Package Name>-> MainActivity.java file
1.Remove these lines from onOptionsItemSelected
method of MainActivity class.
2.RUN project and watch the affects on Action Bar
item selection.
39
HOME EXERCISE
 Create a Project to create a Action
Bar with 3 items.
1. 1st item displays the Wikipedia.
2. 2nd item displays Youtube.
3. 3rd item should be Back link to
return on main fragment.
40
SUMMARY
Creating a Action Bar structure.
 Making the Action Bar menu work.
Understanding the use of MenuInflater.
Handling Action Bar item selection.
Adding Action Bar items in different
ways.
41
Ask me and guide me at
sunmitraeducation@gmail.com.
Share this information with as many
people as possible.
Keep visiting www.sunmitra.com for
programme updates.
THANK YOU…

More Related Content

What's hot

Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interactionEdi Faizal
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptmartinlippert
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your appsJuan C Catalan
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation DrawerEakapong Kattiya
 
Material Design and Backwards Compatibility
Material Design and Backwards CompatibilityMaterial Design and Backwards Compatibility
Material Design and Backwards CompatibilityAngelo Rüggeberg
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
[Individual presentation] android fragment
[Individual presentation] android fragment[Individual presentation] android fragment
[Individual presentation] android fragmentGabriele Vecchia
 
Android app material design from dev's perspective
Android app material design from dev's perspectiveAndroid app material design from dev's perspective
Android app material design from dev's perspectiveDeSmart Agile Software House
 
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
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2stuq
 
Android UI Reference
Android UI ReferenceAndroid UI Reference
Android UI ReferenceGauntFace
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitonsgarbles
 

What's hot (20)

Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interaction
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScript
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your apps
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation Drawer
 
Material Design and Backwards Compatibility
Material Design and Backwards CompatibilityMaterial Design and Backwards Compatibility
Material Design and Backwards Compatibility
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
[Individual presentation] android fragment
[Individual presentation] android fragment[Individual presentation] android fragment
[Individual presentation] android fragment
 
Android app material design from dev's perspective
Android app material design from dev's perspectiveAndroid app material design from dev's perspective
Android app material design from dev's perspective
 
Android
AndroidAndroid
Android
 
Android basic 3 Dialogs
Android basic 3 DialogsAndroid basic 3 Dialogs
Android basic 3 Dialogs
 
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 development session 4 - Fragments
Android development   session 4 - FragmentsAndroid development   session 4 - Fragments
Android development session 4 - Fragments
 
Android basic 2 UI Design
Android basic 2 UI DesignAndroid basic 2 UI Design
Android basic 2 UI Design
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
Android UI Reference
Android UI ReferenceAndroid UI Reference
Android UI Reference
 
25 awt
25 awt25 awt
25 awt
 
HNUH
HNUHHNUH
HNUH
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 

Similar to Handling action bar in Android

Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversUtkarsh Mankad
 
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
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your appVitali Pekelis
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgetsPrajyot Mainkar
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdfImranS18
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversJagdish Gediya
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - AndroidWingston
 
Answer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdfAnswer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdfankitcomputer11
 
Android apps development
Android apps developmentAndroid apps development
Android apps developmentMonir Zzaman
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidDenis Minja
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOORABU HASAN
 
android training_material ravy ramio
android training_material ravy ramioandroid training_material ravy ramio
android training_material ravy ramioslesulvy
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
Rohit android lab projects in suresh gyan vihar
Rohit android lab projects in suresh gyan viharRohit android lab projects in suresh gyan vihar
Rohit android lab projects in suresh gyan viharRohit malav
 

Similar to Handling action bar in Android (20)

Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
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
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your app
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgets
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdf
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
 
Answer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdfAnswer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdf
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
Android Lab
Android LabAndroid Lab
Android Lab
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
 
STYLISH FLOOR
STYLISH FLOORSTYLISH FLOOR
STYLISH FLOOR
 
UIAutomator
UIAutomatorUIAutomator
UIAutomator
 
android training_material ravy ramio
android training_material ravy ramioandroid training_material ravy ramio
android training_material ravy ramio
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Android dev
Android devAndroid dev
Android dev
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Rohit android lab projects in suresh gyan vihar
Rohit android lab projects in suresh gyan viharRohit android lab projects in suresh gyan vihar
Rohit android lab projects in suresh gyan vihar
 

More from indiangarg

Vikars (विकार) explained in Vedic and Modern Context
Vikars (विकार) explained in Vedic and Modern ContextVikars (विकार) explained in Vedic and Modern Context
Vikars (विकार) explained in Vedic and Modern Contextindiangarg
 
Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)
Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)
Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)indiangarg
 
Preparing an Effective CV
Preparing an Effective CVPreparing an Effective CV
Preparing an Effective CVindiangarg
 
Attitude Towards Life
Attitude Towards LifeAttitude Towards Life
Attitude Towards Lifeindiangarg
 
Self confidence
Self confidenceSelf confidence
Self confidenceindiangarg
 
Android the sweetmobility
Android the sweetmobilityAndroid the sweetmobility
Android the sweetmobilityindiangarg
 
Time management
Time managementTime management
Time managementindiangarg
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)indiangarg
 
Android Fundamentals, Architecture and Versions
Android Fundamentals, Architecture and VersionsAndroid Fundamentals, Architecture and Versions
Android Fundamentals, Architecture and Versionsindiangarg
 
Digital Image File Formats
Digital Image File FormatsDigital Image File Formats
Digital Image File Formatsindiangarg
 
Understanding Colors
Understanding ColorsUnderstanding Colors
Understanding Colorsindiangarg
 
Android application development fundamentals
Android application development fundamentalsAndroid application development fundamentals
Android application development fundamentalsindiangarg
 
Mixing Cultures
Mixing CulturesMixing Cultures
Mixing Culturesindiangarg
 

More from indiangarg (18)

Anger.pdf
Anger.pdfAnger.pdf
Anger.pdf
 
Vikars (विकार) explained in Vedic and Modern Context
Vikars (विकार) explained in Vedic and Modern ContextVikars (विकार) explained in Vedic and Modern Context
Vikars (विकार) explained in Vedic and Modern Context
 
Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)
Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)
Some Commonly asked Function/Objects Vs. header files (CBSE 12th Exam)
 
Preparing an Effective CV
Preparing an Effective CVPreparing an Effective CV
Preparing an Effective CV
 
Motivation
MotivationMotivation
Motivation
 
Attitude Towards Life
Attitude Towards LifeAttitude Towards Life
Attitude Towards Life
 
Goal setting
Goal settingGoal setting
Goal setting
 
Self confidence
Self confidenceSelf confidence
Self confidence
 
Android the sweetmobility
Android the sweetmobilityAndroid the sweetmobility
Android the sweetmobility
 
Time management
Time managementTime management
Time management
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
 
Android Fundamentals, Architecture and Versions
Android Fundamentals, Architecture and VersionsAndroid Fundamentals, Architecture and Versions
Android Fundamentals, Architecture and Versions
 
Basics of XML
Basics of XMLBasics of XML
Basics of XML
 
Digital Image File Formats
Digital Image File FormatsDigital Image File Formats
Digital Image File Formats
 
Understanding Colors
Understanding ColorsUnderstanding Colors
Understanding Colors
 
Android application development fundamentals
Android application development fundamentalsAndroid application development fundamentals
Android application development fundamentals
 
07 cof-tea
07 cof-tea07 cof-tea
07 cof-tea
 
Mixing Cultures
Mixing CulturesMixing Cultures
Mixing Cultures
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Handling action bar in Android

  • 1. 1 A Programme Under the Compumitra Series Copyright 2014 © Sunmitra Education Technologies Limited, India Handling Action Bar The action bar is a window feature that identifies the user location, and provides user actions and navigation modes.
  • 2. 2 OUTLINE CREATE A NEW ANDROID PROJECT TO UNDERSTAND THE ACTION BAR CREATING A ACTION BAR STRUCTURE. MAKING THE ACTION BAR WORK CODE EXPLANATION MODIFICATION AND ERROR TRIALS HOME EXERCISE. SUMMARY
  • 3. 3 Create A New Android Project to understand the Action Bar Making.
  • 4. 4 Create New Android Project with 1) Application Name: HandlingActionBar 2) Project Name: HandlingActionBar 3) Package Name: com.company.handlingactionbar 4) Set Minimum Required SDK: API 8 5) Target SDK: API 19 6) Compile With: API 19 7) Theme: Holo Light with… 8) Activity Name: MainActivity 9) And Navigation Type: None CREATE NEW APPLICATION
  • 5. 5 CREATING A ACTION BAR STRUCTURE. To create a menu structure which appears on clicking the menu button on your emulator.
  • 6. 6 <item android:id="@+id/action_google" android:title="@string/google" android:orderInCategory="100" app:showAsAction="never" /> <item android:id="@+id/action_yahoo" android:title="@string/yahoo" android:orderInCategory="101" app:showAsAction="never" /> MODIFICATION IN MENUMAIN.XML FILE  Go to HandlingActionBar->res->menu->main.xml file (XML view). 1) Remove pre-written <item android:id ....... ="never"/> code. 2) Add this code with in <menu> element of main.xml file.
  • 7. 7 <string name="google">Google</string> <string name="yahoo">Yahoo</string> <string name="hello_world">Select any option from Action Bar</string> EDITING STRINGS.XML FILE 1. Go to HandlingActionBar ->res->values->strings.xml file. 2. Click on strings.xml (XML view ). 1) Change value of string app_name to Action Bar 2) Change value of string hello_world to Select any option from Action Bar 3)Add these codes in strings.xml
  • 8. 8 MAKING THE ACTION BAR WORK To make the items defined in a action bar to operate their respective functions.
  • 9. 9 fragment1.xml CREATE NEW RESOURCE FILE: fragment1.xml-1 1. Go to HandlingActionBar ->res->layout. 2. Right click on layout. 3. Select New->File (from the drop down list). 1.A new dialog box appears. Type fragment1.xml in File_name and click on Finish.
  • 10. 10 CREATE NEW RESOURCE FILE: fragment1.xml-2 1.Copy all code from fragment_main.xml and Paste it in fragment1.xml
  • 11. 11 EDITING RESOURCE FILE: fragment1.xml -1 1. Go to HandlingActionBar->res->layout->fragment1.xml file. 2. Click on the Graphical Layout. 3.Delete the default TextView 1.Select the given TextView and press delete.
  • 12. 12 EDITING RESOURCE FILE: fragment1.xml -2 Go to Pallete and drag and drop WebView widget from Composite.
  • 13. 13 android:id="@+id/webView_google" EDITING RESOURCE FILE: fragment1.xml -3 1) Go to fragment1.xml (XML view) file. 2) add android:id="@+id/fragment1" in Layout (if already given, change it to fragment1 ) 4) and change ID to android:id="@+id/webView_google" in WebView
  • 14. 14 CREATE NEW RESOURCE FILE: fragment2.xml-1 1. Go to HandlingActionBar ->res->layout. 2. Right click on layout. 3. Select New->File (from the drop down list). 1.A new dialog box appears. Type fragment2.xml in File_name and click on Finish.
  • 15. 15 CREATE NEW RESOURCE FILE: fragment2.xml-2 Copy all code from fragment1.xml and Paste it in fragment2.xml 2) Change its ID to android:id="@+id/fragment2" in Layout 3) and change ID of WebView to android:id="@+id/webView_yahoo"
  • 16. 16 android:id="@+id/fragment_main " EDITING RESOURCE FILE: fragment_main.xml 1) Go to fragment_main.xml (XML view) file. 2) add android:id="@+id/ fragment_main " in Layout (if already given, change it to fragment_main)
  • 17. 17 public static class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment1, container, false); return rootView; } } public static class Fragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment2, container, false); return rootView; } } JAVA CODE-1 Add this code after the PlaceholderFragment class to create 2 Fragment classes. Go to HandlingActionBar->src-><Package Name>-> MainActivity.java file
  • 18. 18 JAVA CODE-2 getSupportFragmentManager().beginTransaction() .add(R.id.container, new Fragment2()).commit(); getSupportFragmentManager().beginTransaction() .add(R.id.container, new Fragment1()).commit(); 2. Add this code before the pre-written lines in if statement of onCreate method of MainActivity class. pre-written lines in if statement of onCreate method. 1. Import android.webkit.WebView; , android.webkit.WebViewClient;, android.widget.RelativeLayout;.
  • 19. 19 JAVA CODE-3 Now delete the highlighted code (which showing error because we have removed action-settings menu item from menu>main.xml file) from onOptionsItemSelected method of MainActivity class.
  • 20. 20 RelativeLayout layoutmain=(RelativeLayout) findViewById(R.id.fragment_main); RelativeLayout layoutf1 = (RelativeLayout) findViewById(R.id.fragment1); RelativeLayout layoutf2 = (RelativeLayout) findViewById(R.id.fragment2); layoutmain.setVisibility(View.GONE); if (id == R.id.action_google) { layoutf2.setVisibility(View.GONE); layoutf1.setVisibility(View.VISIBLE); WebView webview=(WebView)findViewById(R.id.webView_google); webview.loadUrl("http://www.google.co.in"); webview.setWebViewClient(new WebViewClient()); webview.setHorizontalScrollBarEnabled(false); return true; } else if(id == R.id.action_yahoo) { layoutf2.setVisibility(View.VISIBLE); layoutf1.setVisibility(View.GONE); WebView webview=(WebView)findViewById(R.id.webView_yahoo); webview.loadUrl("http://www.yahoo.com"); webview.setWebViewClient(new WebViewClient()); webview.setHorizontalScrollBarEnabled(false); return true; } JAVA CODE-4 Type this code in onOptionsItemSelected method just before the return statement.
  • 21. 21 JAVA CODE-5 1. Typed code before return statement 2. return statement
  • 22. 22 EDIT MANIFEST.XML FILE-1 1. Go to HandlingActionBar -> AndroidManifest.xml file. 2. Click on the Permissions. 3. Now click on Add Button.
  • 23. 23 EDIT MANIFEST.XML FILE-2 1. A new dialog box appears. Now select Uses Permission and click on OK. 2. Now write android.permission.INTERNET in the Name or you can also select from the drop down window.
  • 24. 24 RUNNING THE APPLICATION ON EMULATOR-1 Run your application on your emulator. 2. Select any one from the given options. 1. Click on default Action bar icon to open Action bar sub menu.
  • 25. 25 RUNNING THE APPLICATION ON EMULATOR-2 Similarly when you will select Google, Google page in WebView of Fragment1 will be displayed on your emulator screen. 1.Select Yahoo, and wait to load page. your emulator screen will display Yahoo page in WebView of Fragment2.
  • 27. 27 CODE EXPLANATION: menu->main.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.company.handlingactionbar.MainActivity" > <item android:id="@+id/action_google" android:title="@string/google" android:orderInCategory="100" app:showAsAction="never" /> <item android:id="@+id/action_yahoo" android:title="@string/yahoo" android:orderInCategory="101" app:showAsAction="never" /> </menu> The first attribute ID allows the item tag to be given a name and referenced in your Java code. Title attribute id is the title or label for the menu button. Menu tag is used to use menu. This keyword Defines, When and how this item should appear as an action item in the Action Bar.
  • 28. 28 CODE EXPLANATION: MainActivity.java-1 public static class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment1, container, false); return rootView; } } public static class Fragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment2, container, false); return rootView; } } Here we creates 2 classes Fragment1 and Fragment2 for fragment1 and fragment2 layout.
  • 29. 29 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new Fragment1()).commit(); getSupportFragmentManager().beginTransaction() .add(R.id.container, new Fragment2()).commit(); getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } These lines adds Fragment1, Fragment2, PlaceholderFragment to MainActivity. CODE EXPLANATION: MainActivity.java-2
  • 30. 30 @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } Inflate the menu; this adds items to the action bar if it is present. Uses the inflate( ) method and the R.menu.main path to our mein.xml file. The R equates to the res folder of our project. CODE EXPLANATION: MainActivity.java-3
  • 31. 31 public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); RelativeLayout layoutmain=(RelativeLayout) findViewById(R.id.fragment_main); RelativeLayout layoutf1 = (RelativeLayout) findViewById(R.id.fragment1); RelativeLayout layoutf2 = (RelativeLayout) findViewById(R.id.fragment2); layoutmain.setVisibility(View.GONE); if (id == R.id.action_google) { layoutf2.setVisibility(View.GONE); layoutf1.setVisibility(View.VISIBLE); CODE EXPLANATION: MainActivity.java-4 Gets the selected Action Bar item ID. This method is called on selection of menu item. Creates the objects of fragment_main, fragment1 and fragment2 layout types. Sets the visibility of layoutmain to hidden Sets the visibility of layoutf1 (fragment1) and Checks, whether selected item ID matches with given item ID or not.
  • 32. 32 WebView webview=(WebView)findViewById(R.id.webView_google); webview.loadUrl("http://www.google.co.in"); webview.setWebViewClient(new WebViewClient()); webview.setHorizontalScrollBarEnabled(false); return true; } else if(id == R.id.action_yahoo) { layoutf2.setVisibility(View.VISIBLE); layoutf1.setVisibility(View.GONE); WebView webview=(WebView)findViewById(R.id.webView_yahoo); webview.loadUrl("http://www.yahoo.com"); webview.setWebViewClient(new WebViewClient()); webview.setHorizontalScrollBarEnabled(false); return true; } return super.onOptionsItemSelected(item); } Creates the object of webview and sets its URL. CODE EXPLANATION: MainActivity.java-5 Checks, whether selected item ID matches with given item ID or not.
  • 34. 34 android:icon="@drawable/google " app:showAsAction="ifRoom" /> android:icon="@drawable/yahoo " app:showAsAction="ifRoom" /> MODIFICATION TRIAL-1 1) Add attribute android:icon="@drawable/ google" in action_google item 1. Go to HandlingActionBar->res->menu->main.xml file (XML view). 3) Add Change attribute value of app:showAsAction to "ifRoom" from both items. 2) Add attribute android:icon="@drawable/yahoo" in action_google item Note: If Minimum Required SDK of your app is Android 3.0 and Above (If your app is not using the Support Library for compatibility) then use android:showAsAction instead of app:showAsAction
  • 35. 35 MODIFICATION TRIAL-2 1. Copy 2 images from http://sunmitra.com/cm- android/actionbar/google.png and http://sunmitra.com/cm-android/actionbar/yahoo.png Samples 1- google.png 2-yahoo.png Pasted files. 3) And paste both images in all drawable folders.
  • 36. 36 RUNNING THE APPLICATION ON EMULATOR-1 Watch the affect on Action Bar items position. Run your application on your emulator .
  • 37. 37 ERROR TRIALS-1 Go to HandlingActionBar->src-><Package Name>-> MainActivity.java file getSupportFragmentManager().beginTransaction() .add(R.id.container, new Fragment2()).commit(); getSupportFragmentManager().beginTransaction() .add(R.id.container, new Fragment1()).commit(); Pre-written lines. Remove these lines from onCreate method of MainActivity class and write again after the pre-written lines. RUN project and watch the affects.
  • 38. 38 else if(id == R.id.action_yahoo) { layoutf2.setVisibility(View.VISIBLE); layoutf1.setVisibility(View.GONE); WebView webview=(WebView)findViewById(R.id.webView_yahoo); webview.loadUrl("http://www.yahoo.com"); webview.setWebViewClient(new WebViewClient()); webview.setHorizontalScrollBarEnabled(false); return true; } ERROR TRIALS-2 Go to HandlingActionBar->src-><Package Name>-> MainActivity.java file 1.Remove these lines from onOptionsItemSelected method of MainActivity class. 2.RUN project and watch the affects on Action Bar item selection.
  • 39. 39 HOME EXERCISE  Create a Project to create a Action Bar with 3 items. 1. 1st item displays the Wikipedia. 2. 2nd item displays Youtube. 3. 3rd item should be Back link to return on main fragment.
  • 40. 40 SUMMARY Creating a Action Bar structure.  Making the Action Bar menu work. Understanding the use of MenuInflater. Handling Action Bar item selection. Adding Action Bar items in different ways.
  • 41. 41 Ask me and guide me at sunmitraeducation@gmail.com. Share this information with as many people as possible. Keep visiting www.sunmitra.com for programme updates. THANK YOU…