Change ActionBar title using Fragments

If you are using Navigation Components from Android Jetpack. The action bar reads the Label attribute for the fragment name. Not sure if this is a proper fix, but if you change the Label text in the Navigation Editor, it will be read by the supportActionBar that is set up in the Activity hosting the fragments.Navigation Editor Attributes Tab


In your activity:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

And in your fragment (You can put it onCreate or onResume):

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

    // Set title bar
    ((MainFragmentActivity) getActivity())
            .setActionBarTitle("Your title");

}

Em Kotlin você pode usar o seguinte código nas funções: onCreateView, onStart e onResume.

override fun onStart() {
   super.onStart()

   (activity as? AppCompatActivity)?.supportActionBar?.title = "Título".
}

Ou se preferir, pode criar uma função de extensão e chamar dentro do Fragment.

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

fun Fragment.setTitle(title: String) {
    (activity as? AppCompatActivity)?.supportActionBar?.title = title
}

Chamada da função de extensão dentro do Fragment.

class StartFragment : Fragment() {

   override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
   ): View? {
       return inflater.inflate(R.layout.fragment_start, container, false)
   }

   override fun onStart() {
       super.onStart()

       this.setTitle(getString(R.string.titulo))
   }
}

In your fragment

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    getActivity().setTitle("Team B");

    View rootView = inflater.inflate(R.layout.fragment_team_b, container, false);

    return rootView;
}