Set a title in Toolbar from fragment in Android

In Kotlin.

In fragment:

(activity as YourActivity).supportActionBar?.title = getString(R.string.your_title)

In activity:

setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)

I do this like this: from the fragment call

getActivity().setTitle("your title");

But where you call it is important, because if each Fragment has it's own title, then one may override the other accidentally, which may be prevented like:

@Override
public void onResume() {
    super.onResume();

    Activity activity = getActivity();
    if (activity != null) {
        activity.setTitle(getString(R.string.my_title));
    }
}

For example, two Fragments of the same Pager can not be in resume-state at the same time.

Also you can "cast", to call any function of your parent Activity like this:

YourActivity mYourActiviy = (YourActivity) getActivity();
mYourActivity.yourActivityFunction(yourParameters);