Usman Saeed
Usman Saeed

Reputation: 863

How to change toolbar in a fragment?

I have two fragments, one is for folder and other is for photos in Tab layout. Photos fragment have many photos when I select one item(picture) I want to change the toolbar entirely like

below

enter image description here

how i will do this and have to listen clicks events on toolbar?

Upvotes: 2

Views: 14136

Answers (3)

Amrish Kakadiya
Amrish Kakadiya

Reputation: 1023

If you want to change your toolbar from a fragment, the code below may help you.

Add toolbar in your fragment XML and then you can change the toolbar of your activity like this:

 Toolbar toolbar = view.findViewById(R.id.toolbar);
 ((MainActivity) getActivity()).getSupportActionBar().hide();

 ((MainActivity) getActivity()).setSupportActionBar(toolbar);

Upvotes: 2

CodeDaily
CodeDaily

Reputation: 766

  • When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().
  • However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.
  • If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

Read Documentation click here.

Upvotes: 2

Babul
Babul

Reputation: 1224

just put it in your fragment get your Actvity toolbar with id and set toolbar as u desired in your fragment

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("title");

Upvotes: 7

Related Questions