0% found this document useful (0 votes)
16 views88 pages

Module - 4: Working With Menus

The document provides an overview of working with menus in Android, detailing various types of menus such as options menus, context menus, and pop-up menus. It explains how to create and manage these menus using Java and XML, including the use of menu groups and responding to menu item selections. Additionally, it covers the structure of XML menu resources and dynamic menu creation techniques.

Uploaded by

santamariya474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views88 pages

Module - 4: Working With Menus

The document provides an overview of working with menus in Android, detailing various types of menus such as options menus, context menus, and pop-up menus. It explains how to create and manage these menus using Java and XML, including the use of menu groups and responding to menu item selections. Additionally, it covers the structure of XML menu resources and dynamic menu creation techniques.

Uploaded by

santamariya474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Module – 4

Working with Menus

BCA/BCS – SEMESTER 6
S.A
Working with Menus
➢Android SDK has extensive support for menus. Menu provides a familiar
and consistent User Interface.
➢It supports regular menus, submenus, context menus, icon menus,
secondary menus and alternative menus
➢Menu is an important User Interface component in Android.
➢Now Android 4.0 has introduced pop-up menus: menus that can be
invoked at any time based on a button click.
➢In Android, menus, much like other resources, can be represented as both
Java object and in XML files.
➢Android generates resource IDs for each of the loaded menu items.
1. Understanding Android Menus

➢The key class for Android menu support is android.view.Menu.


➢The menu object contains a number of menu items and submenus.
➢Menu items are represented by android.view.MenuItem.
➢Submenus are represented by android.view.SubMenu.

Structure of Android menus


related Classes
➢A menu item carries the following attributes:
❖ Name: A string title
❖ Menu item ID: An integer
❖ Group ID: An integer representing which group this item should
be present. Menu items are grouped using group id.
❖Sort order: An integer identifying the order of this menu item
when it is displayed in the menu. Menu items are ordered
according to the sort order.

➢Some of these menu item sort-order number ranges are reserved for
certain kinds of menus. These are called menu categories.
➢The available menu categories are as follows Secondary menu items,
System menu items, alternative menu item, Container menu items.
➢Two callback methods are used to create and respond to menu items:
onCreateOptionsMenu() [to create an options menu] and
onOptionsItemSelected() [to respond to menu items].

2. Creating a Menu
➢Activity is associated with a single menu, Android creates this single menu for
that activity and passes it to the onCreateOptionsMenu() callback method of the
activity class.
➢Menus in Android are also known as options menus.

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// populate menu items
.....
...return true;
}
➢Once the menu items are populated, the code should return true to make the
menu visible. If this method returns false, the menu is invisible.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
//call the base class to include system menus
super.onCreateOptionsMenu(menu);
menu.add(0,1,0,"append");
menu.add(0,2,1,"item2");
menu.add(0,3,2,"clear");
return true;
}
➢The first parameter required for adding a menu item is the group ID (an integer)[to
which group the menu belongs].
➢The second parameter is the menu item ID, which is sent back to the callback function
when that menu item is chosen.
➢The third argument represents the order ID.
➢The last argument is the name or title of the menu item.
Menu.xml file
➢There is one more convenient and preferable way of creating a menu - using an
xml-file.
➢To get a menu which we have created programmatically, we will
create mymenu.xml file in res/menu folder:
<menu >
<item android:id="@+id/item1"
android:title=“@string/str1"/>
<item android:id="@+id/item2"
android:title="@string/str2"/>
<item android:id="@+id/item3"
android:title="@string/str3"/>
</menu>
➢Menu hierarchy is created using the menu tag as the root node and a series of item tags to
specify each menu item.
➢Each menu item node supports a set of attributes
➢To use the resources, implement the MenuInflater class within your
onCreateOptionsMenu() or onCreateContextMenu() event handler.
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater mi= getMenuInflater().;
mi.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1: t1.setText(“The Selected Item is : 1”);
return true;
case R.id.item2: t1.setText(“The Selected Item is : 2”);
return true;
case R.id.item3: t1.setText(“The Selected Item is : 3”);
return true;
default: return super.onOptionsItemSelected(item);
} }
3. Working with Menu Groups
➢Now, let’s look at how to work with menu groups. shows how you add
two groups of menus: Group 1 and Group 2.
public boolean onCreateOptionsMenu(Menu menu)
{
//Group 1
int group1 = 1;
menu.add(group1,1,1,"g1.item1");
menu.add(group1,2,2,"g1.item2");
//Group 2
int group2 = 2;
menu.add(group2,3,3,"g2.item1");
menu.add(group2,4,4,"g2.item2");
return true; // it is important to return true
}
➢A group’s menu items can be manipulated using these methods: removeGroup(id),
setGroupCheckable(id, checkable, exclusive), setGroupEnabled(id,boolean enabled),
setGroupVisible(id,visible)

removeGroup(id)

removeGroup() removes all menu items from that group, given the group ID.
setGroupEnabled(id,boolean enabled)
Menu items can be enabled or disabled in a given group using the setGroupEnabled
method().

setGroupVisible(id,visible)
You can control the visibility of a group of menu items using setGroupVisible().

setGroupCheckable(id, checkable, exclusive)


This method is used to show a check mark on a menu item when that menu item is selected.
When applied to a group, it enables this functionality for all menu items within that group.
4. Responding to Menu Items
➢There are multiple ways of responding to menu item clicks in Android. Responding to
menu items can be done using -
➢ onOptionsItemSelected() method of the activity class;
➢ stand-alone listeners.
➢ intents.
a). Responding to Menu Items through onOptionsItemSelected
➢When a menu item is clicked, Android calls the onOptionsItemSelected()
callback method on the Activity class
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
.....
//for items handled
return true;
//for the rest
...return super.onOptionsItemSelected(item);
}
}
b). Responding to Menu Items Through Listeners
➢Usual responding to menus by overriding onOptionsItemSelected(); this is the
recommended technique for better performance.
➢A listener implies object creation and a registry of the listener.
➢In the first step, you implement the OnMenuClickListener interface.
➢When the menu item is clicked, the menu item calls the onMenuItemClick()
method of the OnMenuClickListener interface.

public class MyResponse implements OnMenuClickListener


{
//some local variable to work on
//...
//Some constructors
@override
boolean onMenuItemClick(MenuItem item){
//code
return true;
}}
➢The onMenuItemClick() method is called when the menu item has been
invoked.
➢This code executes as soon as the menu item is clicked, even before the
onOptionsItemSelected() method is called.
➢This means that the listener code takes precedence over the
onOptionsItemSelected() method.

c). Using an Intent to Respond to Menu Items


➢Responding to menu item can also be done with an intent by using the
MenuItem’s method setIntent(intent).
➢By default, a menu item has no intent associated with it.
➢But when an intent is associated with a menu item, then the default
behavior is to invoke the intent using startActivity(intent).
Working with Other Menu Types
1). Working with Icon Menus
➢Menu icons are graphical elements placed in the options menu shown to users
when they press the Menu button. Icons can be used to represent menu items
instead of and in addition to text.
Limitations of Icon Menus :
1. First, icon menus can’t be used for expanded menus.
2. Second, icon menu items do not support menu item check marks.
3. Third, if the text in an icon menu item is too long, it’s truncated after a certain number
of characters, depending on the size of the display.
➢Icon can be set using the setIcon() method on the MenuItem class.
MenuItem item=menu.add("Add Contacts");
item.setIcon(R.drawable.ic_launcher);
Or
<item
android:id="@+id/m1"
android:icon="@drawable/ic_launcher"
android:title="MicroMax"/>
2). Working with Submenus
➢Submenus are displayed as regular Menu Items, when selected sub menu
reveals more items. It’s a menu within a menu.
➢Traditionally, submenus are displayed in a hierarchical tree layout.
➢Rather than a tree structure, selecting a submenu presents a single
floating window that displays all of its Menu Items.
➢Submenus are added using the addSubMenu() method.
➢setHeaderIcon and setIcon methods are used to specify an icon to
display in the submenu’s header bar or icon menu, respectively.
private void addSubMenu(Menu menu) //java code
{
//Secondary items are shown just like everything else
int Menu1=1;
SubMenu sm = menu.addSubMenu (menu1,1,1,"submenu");
sm.add(menu1,1,1,"sub item1");
sm.add(menu1,2,2,"sub item2");
sm.add(menu1,3,3,"sub item3");
}
Seting SubMenu using main.xml
<menu >
<item
android:id="@+id/TextColor"
android:title="Text Color">
</item>
<item
android:id="@+id/BackColor“
android:title="Back Color">
<menu >
<item
android:id="@+id/BackRed"
android:title=“Red" />

<item
android:id="@+id/BackGreen"
android:title="Green" />
<item
android:id="@+id/BackBlue"
android:title="Blue" />
</menu>
</item>
</menu>
Context Menus
➢A context menu can be accessed by right-clicking a UI element.
➢In Android context menus is accessed by a long click on view.
➢A long click is a mouse click held down slightly longer than usual on.
➢A context menu is represented by ContextMenu class in the Android
menu architecture.
➢Just like a Menu, a ContextMenu can contain a number of menu
items.
➢An activity owns a regular options menu, whereas a view owns a
context menu.
➢So an activity can have only one options menu but many context
menus.
➢Because an activity can contain multiple views, and each view can
have its own context menu, an activity can have as many context menus
as there are views.
Activities, views, and context menus
➢onCreateContextMenu() : - To create a context menu. A context menu is owned by a view.

➢onContextItemSelected() :- Call back method invoked when context menu item is selected.
➢The steps to implement a context menu :
1. Register a view for a context menu in an activity’s onCreate() method.
2. Populate the context menu using onCreateContextMenu().
3. Respond to context menu clicks.

a). Registering a View for a Context Menu


➢The first step in implementing a context menu is to register a view for the context
menu in an activity’s onCreate() method. Here text view is the view used for context
menu.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.Activity_main);
TextView tv = (TextView)this.findViewById(R.id.textViewId);

registerForContextMenu(tv);
}
b). Populating a Context Menu
➢Android calls the onCreateContextMenu() method with a view for populating the
menu.
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo)
{
// statements ;
}
➢The onCreateContextMenu() callback method provides three arguments to work with
1. ContextMenu menu :- a ContextMenu object.
2. View v :- the view (such as the TextView)
3. ContextMenuInfo menuInfo :- the ContextMenuInfo class
➢Example
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo)
{
menu.setHeaderTitle("Sample Context Menu");
menu.add(0,1,1,"item1");
}
c). Responding to Context Menu Items
➢The third step in the implementation of a context menu is responding to context
menu clicks.
➢Android provides a callback method similar to called onContextItemSelected()
for responding to context menu click.
public boolean onContextItemSelected(MenuItem item)
{
if (item.getitemId() = some-menu-item-id)
{
//handle this menu item
return true;
}

}
Dynamic Menus
➢To create dynamic menus, use the onPrepareOptionsMenu() method
that Android provided on an activity class.
➢This method resembles onCreateOptionsMenu() except that it is
called every time a menu is invoked.
➢It is called when the user wants to make a choice. Here Menu items
can be dynamically added when the activity is invoked.
Loading Menus Through XML Files

➢Menus can be defined through XML files, which is possible in


Android because menus are also resources.
➢The XML approach to menu creation offers several advantages, such
as the ability to name menus, order them automatically, and give them
IDs. Follow these steps to work with XML-based menus:
1. Define an XML file with menu tags.
2. Place the file in the /res/menu subdirectory. Android
automatically generates a resource ID for this menu file.
3. Use the resource ID for the menu file to load the XML file
into the menu.
4. Respond to the menu items using the resource IDs generated
for each menu item.
1). Structure of an XML Menu Resource File

➢All menu files start with the same high-level menu tag followed by a series of
group tags.
➢Each of these group tags corresponds to the menu item group.
➢You can specify an ID for the group using the @+id approach.
➢Each menu group has a series of menu items.

2). Inflating XML Menu Resource Files


➢Android provides a class called android.view.MenuInflater to populate Menu
objects from XML files.
➢You use an instance of this MenuInflater to make use of the R.menu.my_menu
resource ID to populate a menu object.

3). Responding to XML-Based Menu Items


➢Responding to menu items are done using onOptionsItemSelected() callback method.
Pop-up Menus in 4.0
➢Android 3.0 introduced another type of menu called a pop-up menu.
➢A pop-up menu can be invoked against any view in response to a UI event.
➢An example of a UI event is a button click or a click on an image view.
➢Pop up Menu is also known as modal menu. This helps in providing overflow style menu.
A Sample XML File for a Pop-up Menu :
<menu >
<item
android:id="@+id/one"
android:title="One"/>
<item
android:id="@+id/two"
android:title="Two"/>

<item
android:id="@+id/three"
android:title="Three"/>
</menu>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
Working with a Pop-up Menu :
private void showPopupMenu()
{
TextView tv = getTextView();
PopupMenu popup = new PopupMenu(this, tv);
popup.inflate(R.menu.popup_menu);
popup.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem item)
{
appendMenuItemText(item);
return true;
}});
popup.show();
}
❖A pop-up menu is used on demand, whereas an options menu is
always available.
❖A pop-up menu is anchored to a view, whereas an options menu
belong to the entire activity.
❖A pop-up menu uses its own menu item callback, whereas the
options menu uses the onOptionsItemSelected() callback on the
activity.
Working with Toast
➢A Toast is like an alert dialog that has a message and displays for a certain
amount of time and then disappears after timeout.
➢It does not have any buttons.
➢Toast is also known as transient alert message. show() method is used to display
toast.
➢It provides a simple message about an operation performed.
Synatx :

Toast.makeText(context, text, duration)).show()

Parameters :
Context : Name of the activity which invoke the Toast.
Text : Message for display.
Duration : how long the toast will show. It contains 2 value
Toast.LENGTH_LONG
Toast.LENGTH_SHORT
Example :
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.but1);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
s1="Welcome to Android";
Toast.makeText(MainActivity.this,
s1,Toast.LENGTH_LONG).show();
}
});}

setGravity(int,int,int) method is used to set the position of the message onscreen


Output :
Module – 4
Working with Fragments

BCA/BCS – SEMESTER 6
S.A
1). What Is a Fragment?
➢A fragment is a reusable class implementing a portion of an activity.
➢A Fragment typically defines a part of a user interface and it has its own layout
and life cycle. It’s flexible and reusable. A Fragment can be used in multiple
activities.
➢Fragments must be embedded in activities; they cannot run independently of
activities. A fragment is an independent Android component which can be used by
an activity.
➢It is also possible to define fragments without an user interface, i.e., headless
fragments.
➢Android devices exists in a variety of screen sizes and densities.
➢Fragments also support different layout for landscape and portrait orientation on
a smartphone.
➢It is possible to dynamically add and remove fragments from an
activity. The usage of fragments allows to design very flexible user
interfaces. Multiple fragments can be used in an activity to create multi-
pane UI.
➢Fragments implement modularity. Its modular and reusable.
Fragments In Android
➢Here are the important things to understand about fragments:
❖A Fragment is a combination of an XML layout file and a java class much
like an Activity.
❖Using the support library, fragments are supported back to all relevant
Android versions.
❖Fragments encapsulate views and logic so that it is easier to reuse within
activities.

❖Reusing View and Logic Components - Fragments enable re-use of parts


of your screen including views and event logic
❖Tablet Support - Often within apps, the tablet version of an activity has
different layout from the phone Fragments enable device-specific activities to
reuse shared elements.
❖Screen Orientation - Often within apps, the portrait version of an activity
has a substantially different layout from the landscape version. Fragments
enable both orientations to reuse shared elements while also having
differences.
Activity and Fragment
❖Activities are navigation controllers primarily responsible
for:
✓Navigation to other activities through intents.
✓Hiding and showing relevant fragments using the fragment
manager.
✓Receiving data from intents and passing data between
fragments.
❖Fragments are content controllers and contain most views,
layouts, and event logic including:
✓ Layouts and views displaying relevant app content.
✓ Event handling logic associated with relevant views.
➢In a fragment-based architecture, the activities are for
navigation and the fragments are for views and logic.
2). A Fragment’s Lifecycle
➢A fragment has its own life cycle, but it is always connected to the life
cycle of the activity which uses the fragment.
➢If an activity stops, its fragments are also stopped. If an activity is
destroyed, its fragments are also destroyed.
Method Description
onAttach() The fragment instance is associated with an activity instance. The
fragment and the activity is not fully initialized here. This method
is a reference to the activity which uses the fragment for further
initialization work.
onCreate() Fragment is created. The onCreate() method is called after
the onCreate() method of the activity but before
theonCreateView() method of the fragment.
onCreateView() The fragment instance creates its view hierarchy. In the
onCreateView() method the fragment creates its user interface. In
this method you should not interactive with the activity, the
activity is not yet fully initialized.
onActivityCreated() The onActivityCreated() is called after the
onCreateView() method when the host activity is created.

onStart() The onStart() method is called once the fragment gets visible.
onResume() Fragment becomes active.
onPause() Fragment is visible but becomes not active anymore, e.g., if
another activity is animating on top of the activity which contains
the fragment.
onStop() Fragment becomes not visible.
onDestroyView() Destroys the view of the fragment. If the fragment is recreated
from the backstack this method is called and afterwards the
onCreateView method.
onDestroy() Final clean up of the applications state.
onDetach() Detached from Activity.
3).FragmentTransactions and the Fragment
Back Stack
➢Actions such as add, remove, replace etc. can be performed on fragments in
response to user interaction.
➢Scene defines the given state of applications UI. Animated change between two
scenes is called transition. Each set of changes committed to the activity is called
a transaction and transactions are performed using APIs in FragmentTransaction.
➢Each transaction can be saved to a back stack managed by the activity, allowing
the user to navigate backward through the fragment changes (similar to navigating
backward through activities).
➢An instance of FragmentTransaction is acquired from the FragmentManager
FragmentManager fm= getFragmentManager();
FragmentTransaction ft = fm. beginTransaction();
➢To apply the transaction to the activity, you must call commit().
➢Before calling commit(), call addToBackStack(), in order to add the transaction
to a back stack of fragment transactions.
➢The back stack is managed by the activity and it allows the user to return to the
previous fragment state, by pressing the Back button.
➢Fragment Transaction Methods.

1. add(int containerViewId, Fragment fragment): Adds a given fragment to


activity state.
2. attach(Fragment fragment) : The detached fragment can be re- attached by
using this method.
3. detach(Fragment ft) : Detaches the given fragment from UI.
4. remove(Fragment fragment) : Removes the given fragment from UI and
container.
5. replace(int containerViewId, Fragment fragment) : For the given
container view id, we can replace existing fragment by new given fragment.
6. commit(): Transaction is committed.
Fragment Sample Code – N.B

// Create new fragment and transaction


Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager(). beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

To define a new fragment either extend the android.app.Fragment class or one of


its subclasses.
Subclasses - ListFragment – It displays a list of items managed by adapter
DialogFragment – It displays a floating dialog
PreferenceFragment – It displays hierarchy of preference objects
as a list.
public class DetailFragment extends Fragment
{
//fragment-code
}
Back Stack

➢An android application is composed of multiple Activities.


➢New activities are launched using intents.
➢Older ones are either destroyed or placed on a back stack.
➢Back stack is a data structure which holds activities in the background which user
can navigate to using back button.
➢Back stack works in the last in first out mode.
➢It can be cleared in case of low memory.

Task
➢Task is a collection of activities that user perform while doing a job.
➢An activity is launched in a new task from the home screen.
➢By default all the activities in an application belong to the same task.
➢Activities in a task can exist in the foreground, background as well as on back stack.
➢By calling addToBackStack(), the transaction is saved to the back stack so the
user can reverse the transaction and bring back the previous fragment by pressing
the Back button.
➢To retrieve fragments from the back stack, you must
override onBackPressed() in the main activity class:

➢public void onBackPressed() {


if (getFragmentManager().getBackStackEntryCount() > 0)
{
getFragmentManager().popBackStack();
}
}
➢ If there is no previous activity, pressing Back causes the app to close.
➢ If you do not call addToBackStack() after performing a transaction and
committing it, then the user cannot navigate to the previous state.
4). The FragmentManager
➢To manage the fragments in the activity FragmentManager is required.
➢To use it, call getFragmentManager() from the activity.
➢Functions in FragmentManager include:
➢Get fragments that exist in the activity, with findFragmentById()
or findFragmentByTag() .
➢Pop fragments off the back stack, with popBackStack() .
➢Register a listener for changes to the back stack,
with addOnBackStackChangedListener().
➢FragmentManager Can be used to open a FragmentTransaction, which
allows to perform transactions, such as add and remove fragments.
Fragment Manager Class
➢FragmentManager
which is used to create transactions for adding, removing or replacing
fragments.
➢getFragmentManager();
Return the FragmentManager for interacting with fragments
associated with this activity.
➢fragmentManager.beginTransaction();
Start a series of edit operations on the Fragments associated with this
FragmentManager.
➢fragmentTransaction.replace(R.id.fragmentcontainer,mFeedFragment);
Replaces the current fragment with another one on the layout using
id.
➢fragmentTransaction.addToBackStack(null);
Add this transaction to the back stack. This means that the transaction
will be remembered after it is committed.
5). Saving Fragment State
➢ Fragment.SavedState class was introduced in Android 3.2: .
➢saveFragmentInstanceState() method of FragmentManager returns an object representing
the state of that fragment.
➢onSaveInstanceState() callback will be invoked when it detects that a configuration
change is happening.
➢The onSaveInstanceState() callback will be called prior to the call to onStop().
➢On this call back the existing state can be accessed and saved into a Bundle object.
➢ This object will get passed in to both of the other callbacks (onCreate() and
onRestoreInstanceState()) when the activity is re-created.
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
//save fragment state
}
6). Persistence of Fragments
➢When device rotates the fragments rotate right along with it.
➢During a device rotation not only does the activity get destroyed and recreated,
but the fragments also gets destroyed and recreated.
➢After configuration change, activity gets recreated and fragment gets reattached
to the new activity.
➢Android will take care of fragments that are in the fragment manager, by saving
them and restoring them when the activity is being re-created.
➢Fragment should only communicate with their direct parent activity.
➢Fragments should be modular, reusable and standalone components.
➢The fragments are reconstructed for you after reconfiguration.
➢Android save the arguments bundle and the knowledge of which type of fragment
it was for restoring purpose
➢Fragment can contain nested child fragments.
7). startActivity() and startActivityForResult()
Fragment has startActivity(intent) method and startActivityForResult() method.
➢When a result is passed back, it will cause the onActivityResult() callback to start
the fragment that started the activity.
➢The startActivity () is used to start a new activity.
public void startActivity (Intent intent, Bundle options)
{}
➢The new activity will be placed at the top of activity stack.
➢startActivityForResult() is used when it is needed to return the result value.
public void startActivityForResult (Intent intent, int requestCode)
{}
➢setResult is used to return data back to parent. It will supply a result code –
RESULT_CANCELLED, RESULT_OK
setTargetFragment ()
➢ setTargetFragment (ParentFragment instance, RequestCode)
from ParentFragment is used to communicate from one fragment to
another fragment .
➢ This method may be used, if this fragment is being started by another,
and it wants to give a result back to the first.
➢ void setTargetFragment (Fragment fragment, int requestCode){}
➢ The target set here is retained across instances
via FragmentManager.putFragment().

➢ getTargetFragment- Fragment getTargetFragment ()


➢ It return the target fragment set by setTargetFragment ().
➢ Working Flow:-
➢ If we want to communicate from one fragment to another fragment then
from First fragment we have to use setTargetFragment (FirstFragment
instance ,RequestCode).
➢ After that use show() method of fragment.
➢ On Second Fragment we have to use getTargetFragment() which return
fragment instance.
➢ Then use onActivityResult ().
Module – 4
Working with Action Bar

BCA/BCS SEMESTER 6
S.A
Action Bar
➢The action bar is an Android UI pattern [design element] that is used to
provide a consistent user interface for key features such as tabs, application
identity, menus, and search. It is also known as app bar.
➢The ActionBar APIs introduce UI themes to provide a consistent look and
feel that allow for tabbed user interfaces.
➢The action bar is a dedicated piece of space at the top of each screen that is
generally persistent throughout the app.
➢The action bar tries to display all of its tabs concurrently and make all the
tabs equal in size based on the width of the widest tab label.
➢It has the powerful capabilities like adapting to screen configurations
(landscape & portrait).
General Organization

➢In Android 3.0 (API level 11), Google introduced the ActionBar APIs to the
Android platform.
➢Action bar mainly contains four functional areas. They are app icon,
view control, action buttons and action overflow.
1. App Icon – App branding logo or icon will be displayed here.
2. View Control – A dedicated space to display app title. It also
provides option to switch between views by adding spinner or
tabbed navigation.
3. Action Buttons – Some important actions of the app can be
added here.
4. Action Overflow – All unimportant action will be shown as a
menu in this part.
Layout Considerations for Split Action Bars

➢There can be multiple action bars, that can be


placed in three possible locations for action bar
content:
❖ Main action bar
❖ Top bar
❖ Bottom bar
➢To allow the user to quickly switch between the
views your app provides, use tabs or a spinner in
the top bar.
➢To display actions and the action overflow, use
the bottom bar.
Action Buttons

➢Action buttons on the action bar surface refers app's most important
activities. It shows the actions used most often
➢Depending on available screen space, the system shows the most
important actions as action buttons and moves the rest to the action
overflow.
Action overflow
➢ The action overflow in the action bar provides access to app's less
frequently used actions.

Action overflow is pinned


to the right side.
Supporting Library files :
➢Support Library classes should be imported to implement Actionbar.
a). Add Tabs to the Action Bar

➢Action bar tabs offer users a familiar interface for navigating between and
identifying sibling screens in your app. Tabs enable navigation.
➢To create tabs using ActionBar :
1) In the OnCreate method of an Activity – NavigationMode on
the ActionBar must be set toto ActionBar.NavigationModeTabs
2) Create a new tab using ActionBar.NewTab().
3) Assign event handlers or provide a custom ActionBar.TabListener
implementation that will respond to the events that are raised by
user.
4) Add the tab that was created in the previous step to the ActionBar.
1) .Action Bar Navigation Modes :
➢In Tab navigation, navigation mode must be set by passing
NAVIGATION_MODE_TABS as the parameter.
➢There three different navigation type supported:
❖ ActionBar.NAVIGATION_MODE_LIST
❖ ActionBar.NAVIGATION_MODE_STANDARD
❖ ActionBar.NAVIGATION_MODE_TAB
ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
SetContentView(Resource.Layout.Main);
Obtaining an Action Bar Instance :
➢action bar of an activity is accessed by calling getActionbar() on the
activity.
➢Here is that line of code:
ActionBar bar = this.getActionBar();
2). Setting up the Tabs :
➢We’ve got three tabs that are displayed in the action bar.
➢Here’s the code for setting up the tabs:

➢Get an instance of our Action Bar, set the navigation mode to Tabs,
disable displaying the activity’s title and then create the Tab objects
3). Assign event handlers or Listener:
➢Activity should implements the listener so that when user selects
a tab it shows the relative fragment.
➢Each tab in the action bar should be associated with a fragment.
➢When the user selects a tab, the application will display the fragment
that is associated with the tab.
➢ActionBar.TabListener interface provides three callback methods that
Android will invoke when the state of the tab changes:
➢OnTabSelected - This method is called when the user selects the
tab. It should display the fragment.
➢OnTabReselected - This method is called when the tab is already
selected but is selected again by the user. This callback is typically
used to refresh/update the displayed fragment.
➢OnTabUnselected - This method is called when the user selects
another tab. This callback is used to save the state in the displayed
fragment before it disappears.
Example :-
ActionBar ab = getSupportActionBar();

ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

ActionBar.TabListener tabListener = new ActionBar.TabListener()


{
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction ft)
{
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab,FragmentTransaction ft)
{
// hide the given tab
}

public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft)


{
// probably ignore this event
}
};
// Add 2 tabs, specifying the tab's text and TabListener
ActionBar.Tab t_one = ActionBar.newTab();
ActionBar.Tab t_two = ActionBar.newTab();

t_one .setText("Tab 1”);


t_one.setTabListener(tabListener));
t_two .setText("Tab 2”);
t_two.setTabListener(tabListener));

actionBar.addTab(t_one);
actionBar.addTab(t_two);

}
4). Add tab to the Action Bar:
➢Add the tab that was created in the previous step to the ActionBar
using :
ActionBar.addTab(tab1)
➢Example :-
actionBar.addTab(t_one);
actionBar.addTab(t_two);
actionBar.addTab(t_three);
2. Action Bar and Menu Interaction
➢To add actions to the action bar, create a XML file in
the res/menu directory where actions are defined.
➢It is possible to define the actions in Java code, but you will write less
code if you use XML.
<menu >
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_record"
android:icon="@drawable/ic_action_video"
android:title="@string/action_record"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_save"
android:icon="@drawable/ic_action_save"
android:title="@string/action_save"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_label"
android:icon="@drawable/ic_action_new_label"
android:title="@string/action_label"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:showAsAction="never" />
</menu>
1). Menu Items as Actions :

➢ Some of the menu items are assigned to appear directly on the action
bar. These menu items are indicated with the tag showAsAction.
➢Here the important xml attributes should be known are
❖ android:icon – Defines the icon of the action item.
❖ android:title – Title for the icon.
❖ android:showAsAction – Defines the visibility of the action item.
It accepts following values.
ifRoom Displays the icon if there is space available on the screen
never Never places this icon on the action bar
Forces to display the icon always irrespective of space available.
always
This way is not suggested.
Displays a text along with the icon. Normally the text value
withText
defined by android:title will be displayed
Defines the action layout associated with it. This action view
collapseActionView
defined using android:actionLayout orandroid:actionViewClass
3. List Navigation Action Bar Activity
➢You need the following additional files to implement list action bar
navigation activity :
❖ SimpleSpinnerArrayAdapter.java: This class provides the rows
required by a drop-down navigation list.
❖ ListListener.java: Acts as a listener to the list navigation activity.
❖ ListNavigationActionBarActivity.java: Implements the list
navigation action bar activity.
1). Creating a Spinner Adapter :

➢A spinner helps to access one value from a set of values. It will


displays a drop down menu when pressed.
➢To be able to initialize the action bar with list navigation mode, you
need the following two things:
➢A spinner adapter
➢A list navigation listener
➢SimpleSpinnerArrayAdapter implements the SpinnerAdapter
interface.
➢Example :
public class SimpleSpinnerArrayAdapter extends ArrayAdapter<String>
implements SpinnerAdapter
{
public SimpleSpinnerArrayAdapter(Context ctx)
{
//code
}
}
2). Creating a List Listener :
➢When user selects an item in a list, system calls onItemClick() on the
OnItemClickListener().

➢Example :-
public class ListListener extends BaseListener implements
ActionBar.OnNavigationListener
{
public ListListener(Context ctx, IReportBack target)
{
}
}}
3). Setting Up a List Action Bar :
➢This class is very similar to the tabbed activity.
➢Example :-

public class ListNavigationActionBarActivity extends


BaseActionBarActivity
{
public ListNavigationActionBarActivity()
{
}
}
}
4. Standard Navigation Action Bar Activity
➢After setting an activity, set its action bar navigation mode as
standard.
➢StandardNavigationActionBarActivity.java: This is the
implementation file for configuring the action bar as a standard
navigation mode action bar
➢Tabbed listeners are used while setting up the tabbed action bar and list
listeners for setting up the list navigation action bar.
➢Example :
public class StandardNavigationActionBarActivity extends
BaseActionBarActivity
{
public StandardNavigationActionBarActivity()
{
}
}
5. Action Bar and Search View
➢Search View is a widget that provides a user interface for the user to
enter a search query and submit a request to a search provider.
➢Shows a list of query suggestions or results if available, and allows the
user to pick a suggestion or result to launch into.
➢Other features available for the search dialog and widget include:
❖ Voice search
❖ Search suggestions based on recent queries
1) The search dialog is a UI component that's
controlled by the Android system.
✓ When activated by the user, the search
dialog appears at the top of the activity.
✓ The Android system controls all events in
the search dialog.
✓ When the user submits a query, the system delivers the query
to the activity that you specify to handle searches.
✓ The dialog can also provide search suggestions while the user
types.
2). The search widget is an instance of SearchView placed anywhere
in your layout.
✓ By default, the search widget behaves like a standard EditText .
a). Add the Search View to the App Bar
➢To add a SearchView widget to the app bar, create a file
named res/menu/options_menu.xml in your project and add the
following code to the file.
➢This code defines how to create the search item, such as the icon to use
and the title of the item.
➢The collapseActionView attribute allows your SearchView to expand
to take up the whole app bar and collapse back down into a normal app
bar item when not in use.
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:queryHint="Search Here"
android:layout_alignParentTop="true"
/>
Module – 4
Working with Dialogs

BSC/BCA – SEMESTER 6
S.A
Working with Dialogs
➢A dialog is a smaller window that pops up in front of the current
window to show an urgent message, to prompt the user for a piece of
input, or to show some sort of status like the progress of a download.
➢ The user is generally expected to interact with the dialog and then
return to the window underneath to continue with the application.
➢Dialogs that are explicitly supported in Android include the
❖ alert, prompt
❖ pick-list
❖ single-choice
❖ multiple-choice
❖ Progress
❖ Time-picker and date-picker dialogs. – to select date or time
➢ Android also supports custom dialogs for other needs.
Using Dialogs in Android
➢Dialogs in Android are asynchronous, which provides flexibility.
➢In android dialogs, application has the ability to dismiss the dialog from code,
which is powerful.
➢Android AlertDialog class can be used to display the dialog message with OK
and Cancel buttons. It can be used to interrupt and ask the user about his/her choice
to continue or discontinue.
➢Android AlertDialog is composed of three regions: title, content area and
action buttons. The DialogFragment manages and handles dialog correctly.
➢ Title – Title is optional. Title area displays the title of the message.

➢ Content area – This area displays the message, list, checkbox etc. that is displayed
to the user.

➢ Action Buttons – The maximum number of action buttons supported in a dialog


box is three. It includes positive button, negative button and neutral button.
➢ Positive :Positive button accepts and continue with the action (the "OK" action).

➢ Negative :Negative button is used to cancel the action.

➢ Neutral: Neutral button is used when the user want to neither proceed nor cancel
the action. For example. the action might be "Remind me later.“

The three kind of lists available in AlertDialog API are –

➢ A traditional single choice list

➢ A persistent single choice list[radio button]

➢ A persistent multiple choice list [check box]


Understanding Dialog Fragments

1). DialogFragment Basics


➢Dialog-related functionality uses a class called DialogFragment.
➢A DialogFragment is derived from the class Fragment and behaves much like a
fragment.
public class MyDialogFragment extends DialogFragment
{
...
}
public void showDialog()
{
MyDialogFragment mdf
=MyDialogFragment.newInstance(arg1,arg2);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mdf.show(ft,"my-dialog-tag");
}
}
➢the steps to show a dialog fragment are as follows:
1. Create a dialog fragment.
2. Get a fragment transaction.
3. Show the dialog using the fragment transaction.
a). Constructing a Dialog Fragment

➢A dialog fragment uses same rules and as fragments.


➢Inside that newInstance() method, use the default constructor for
dialog fragment, and then add an argument bundle that contains
passed-in parameters.
Overriding onCreateView
➢To provide the view hierarchy for the dialog it is required to override
any of the two methods given below.
➢The first option is to override onCreateView() and return a view.
➢The second option is to override onCreateDialog() and return a
dialog .

public View onCreateView()


{
View rootView = inflater.inflate();
getDialog().setTitle("DialogFragment Tutorial");
return rootView;
}
Overriding onCreateDialog
➢As an alternate to supplying a view in onCreateView(), override
onCreateDialog() and supply a dialog instance.

public class AlertFragment extends DialogFragment


{
@Override
public Dialog onCreateDialog(Bundle bundle)
{
AlertDialog.Builder b= new AlertDialog.Builder(getActivity());
.setIcon(R.drawable.ic_launcher)
.setTitle("Alert DialogFragment")
.setMessage("Alert DialogFragment Tutorial")
// Positive button
.setPositiveButton("OK", newDialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// code
}
});
// Negative Button
.setNegativeButton("Cancel", newDialogInterface. OnClickListener ()
{
public void onClick(DialogInterface dialog,int which)
{
// code
}
});
AlertDialog dl = b1.create();
dl.show();

}
}
}
b). Displaying a Dialog Fragment
➢Once a dialog fragment is constructed, a fragment transaction is needed to show it.
➢Operations on dialog fragments are conducted through fragment transactions.
➢The show() method on a dialog fragment takes a fragment transaction as an input.
➢To show the dialog box, create an instance of the DialogFragment and call show() method
by passing the FragmentManager and a tag name for the dialog fragment.

public int show(FragmentTransaction transaction, String tag)


public int show(FragmentManager manager, String tag)
➢ The first show() method displays the dialog by adding this fragment to the passed-in
transaction with the specified tag. This method then returns the identifier of the
committed transaction.
➢ Second show () method This is a shortcut method. However, when you use this second
method, you don’t have an option to add the transaction to the back stack.
➢Even if the device rotates when a dialog is being displayed, the dialog is
reproduced without you performing any state management.
➢The dialog fragment also offers methods to control the frame in which the
dialog’s view is displayed, such as the title and the appearance of the frame.
➢ The system dismisses the dialog when the user touches an item in a
dialog list, except. Otherwise, it cab be manually dismissed by
calling dismiss() on your DialogFragment.

You might also like