Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTitle doesn't work in fragment

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.

like image 348
JDN96 Avatar asked Apr 06 '16 19:04

JDN96


2 Answers

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.

like image 197
Man Avatar answered Sep 28 '22 16:09

Man


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;
    }


}
like image 43
Sreehari Avatar answered Sep 28 '22 16:09

Sreehari