Android

Display Menu items in ActionBar when using Fragment

Display Menu items in Fragment ActionBar

When Implementing Fragment screen, If it require to display Menu Items only specific to that Fragment screen.

If you just write the following code…

       
        @Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.done_actions_menu, menu);
	}

	/**
	 * On selecting action bar icons
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Take appropriate action for each action item click
		switch (item.getItemId()) {
		case R.id.action_done:
			Log.d(TAG, "Done button clicked...");
                        //action code
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

It won’t display Menu items in ActionBar.

To display Menu Items you should also override OnCreate method of Fragment class as shown below

     
       @Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}

Hope it helps somebody…

cheers  🙂

Leave a Reply

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