I have a fragment where I try to change the title of the actionbar. This worked until i added setHasOptionsMenu(true)
to the fragment.
How can i solve this? Because I need the optionsmenu
in the fragment.
In fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity)getActivity()).setActionBarTitle(getString(R.string.title_view_tree));
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_view_tree, container, false);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_view_tree,menu);
super.onCreateOptionsMenu(menu,inflater);
}
In MainActivity:
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
When I disable setHasOptionsMenu(true)
by using //
then the title of the actionbar
changes correctly.
call the setActionBarTitle from Fragment's onCreateOptionMenu.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main4, menu);
((MainActivity)getActivity()).setActionBarTitle(getString(R.string.title_view_tree));
super.onCreateOptionsMenu(menu, inflater);
}
I'd recommend to use callback interface for interacting with activity.
Do the following changes to handle both Title and Menu in Fragment
public class YourFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_xml_contents, container, false);
((HostedActivity) getActivity()).setFragmentTitle(getActivity().getString(R.string.frag_title));
setHasOptionsMenu(true);
.....
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.profile_menu_xml, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
//....... action for menu item
return false;
default:
break;
}
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With