0

Hello developers out there,

I have an activity which contains several fragments. I want, that when the fragment changes, also the title of the toolbar changes. How probably many of you know

toolbar.setTitle("title")

does nothing while

getSupportActionBar().setTitle("title")

works fine.

But I can't call getSupportActionBar() from my fragment, because it's no static method. Does anybody has an idea how could solve this?

Thanks too you Greetings Pumpanickel

Pumpanickel
  • 91
  • 2
  • 10

4 Answers4

5
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("title");

just make sure you don't call that before the onActivityCreated() so you don't get an exception

Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
  • i dont get why this is working and without a cast to appcombatactivity it doesnt, but its fine for now, thanks a lot :) – Pumpanickel Nov 18 '18 at 17:03
  • these methods are inherited in the activity by the superclass AppCompatActivity. By adding the cast you know you'll be getting access to those methods even when you're inside the fragment – Nikos Hidalgo Nov 18 '18 at 17:13
1

You could do something like this.

 getActivity().getSupportActionBar().setTitle("title")
Ramesh Yankati
  • 1,197
  • 9
  • 13
1

Works for me in each onCreate of fragments use it this:

getActivity.setTitle("Your title"); 
Ju Grigori
  • 143
  • 1
  • 6
0

my answer is based on that .. u want to change the toolbar title in your activity from your fargment so the toolbar is in your activity not in your fragment

well ,, u can use a toolbar in a fragment so u make the toolbar in a fragment or check which fragment is visible and change the toolbar title by its cases and this topic will help u get currently displayed fragment

Muhammad
  • 601
  • 2
  • 9
  • 18