Inherited the MainActivity from some BasicActivity in order to avoid code repetition in new BasicActivity activities. In BasicActivity made a public method for changing the title, which is displayed in the toolbar:

 public class BasicActivity extends AppCompatActivity { private Toolbar toolbar; // ... protected void initToolbar() { toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(R.string.app_name); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener(){ // ... } // ... public void changeToolbarTitle(String title){ toolbar.setTitle(title); } } 

From the MainActivity , or rather from onCreate() , this method can be easily called:

 changeToolbarTitle("test"); 

But how to do the same from other classes that are not Activity (for example, from the heir Fragment )? I tried:

 MainActivity.this.changeToolbarTitle("Test"); 
  • getActivity().changeToolbarTitle("Test"); ? - pavlofff
  • No, you can Cannot resolve method if you call from the fragment onCreateView . - Hokov Gleb

1 answer 1

The fragment has a getActivity() method that will return an Activity . If your fragment is bound to BasicActivity , then the result of the method is easily applied to this class:

 BasicActivity activity = (BasicActivity)getActivity(); 

then you can change the title directly from the fragment:

 activity.changeToolbarTitle("lol") 

This method is unsafe in that the fragment can be located in any activity. Thus, there is no guarantee that getActivity() will return a result that calmly casts without a ClassCastException . Therefore, I advise you to make some BasicFragment , which will have a method:

 public BasicActivity getBaseActivity() { return (BasicActivity)getActivity(); } 

And in the application itself, as a rule, use only the heirs of BasicActivity and BasicFragment

  • Thank you for your reply! Everything is working. - Bokov Gleb
  • @GurebuBokofu if the answer helped you, mark it with a solution. - Sergey Gornostaev