Reputation: 358
So my problem is that when the user clicks the contact, that takes me to the other fragment but the title on the action bar still with the favorite title and not the new one, how to change that title?
I have already try to use setTitle
on the click method but still not working.
Upvotes: 22
Views: 44892
Reputation: 141
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))
}
}
Upvotes: 4
Reputation: 11
for java use
to change the title of the toolbar
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
((MainActivity) getActivity()).getSupportActionBar().setTitle("hello word");
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
Upvotes: 1
Reputation: 196
NOT_A_PROGRAMMER's answer is right but when you come back to the previous activity or fragment the Title remains the same.
Here is my solution for that.
@Override
public void onStop() {
super.onStop();
((MPOSTransactionActivity) getActivity()).setActionBarTitle(getString(//NAME));
}
Upvotes: 1
Reputation: 448
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.
Upvotes: 11
Reputation: 6981
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;
}
Upvotes: 25
Reputation: 1924
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");
}
Upvotes: 70