Android Coding Tips: How to Create Options Menu on Child Activity inside an ActivityGroup

Android ActivityGroup is a screen that contains and run multiple embedded child activities. It works just like a normal Activity but on ActivityGroup, we can create multiple child activities and  the ActivityGroup will be the parent activity. Creating options menu on a normal activity and a child activity inside an ActivityGroup is different.  To create options menu, first override the onCreateOptionsMenu and onOptionsItemSelected method on parent activity, then override the two methods on child activity as usual.

On parent activity

public class TestGroup extends ActivityGroup {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//start child activity
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    return getLocalActivityManager().getCurrentActivity().onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
	    return getLocalActivityManager().getCurrentActivity().onMenuItemSelected(featureId, item);
	}
}

On child activity

public class ChildActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//your code goes here
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//add menu here
		//do not call super.onCreateOptionsMenu(menu) here

	    return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		//handle on menu item selected here
		//do not call super.onMenuItemSelected(featureId, item) here

	    return true;
	}
}

As we can see from the two code snippets above, onCreateOptionsMenu and onMenuItemSelected are also called in the parent activity. This has to be done because menu can be handled in the parent activity but created in child activity.

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. Sam says

    I’ve tried above code,but i’m getting the same menu for both activity, I have different menu.xml for each activity, please let me know how to fix this…

  2. ranjith says

    hai…. very helpful one.. i use the option menus to navigate from one activity to another activity…

    where the codes to be placed??? can you hel me…

Leave a Reply

Your email address will not be published. Required fields are marked *