7

In my app, I use NoActionBar style, and I want to add action Bar to the one of my fragment.

In Activity I can do this like:

public class MyActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

How do this in fragment ?

I tried so:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

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

        Toolbar actionBar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
        ((AppCompatActivity) getActivity()).setSupportActionBar(actionBar);

        return inflater.inflate(R.layout.fragment_training, container, false);

    }

But it doesn't work.

UPD I think the problem in this line:

Toolbar actionBar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(actionBar);
swiftBoy
  • 35,607
  • 26
  • 136
  • 135
Alexandr Svetenco
  • 171
  • 1
  • 2
  • 10
  • Can you further explain what you mean by doesn't work? Does the bar just not appear? Are there any errors? – Fencer04 Sep 15 '16 at 18:08
  • Bar just not appear... It mean that the toolbar (my_app_bar from fragment layout) appears. But this toolbar is not filled with items from main_menu – Alexandr Svetenco Sep 16 '16 at 06:32

2 Answers2

10

Old question)), should be:

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

     //Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
     //((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
     //return inflater.inflate(R.layout.fragment_training, container, false);

     View v = inflater.inflate(r.layout.fragment_training, container, false);
     Toolbar toolbar = (Toolbar) v.findviewbyid(r.id.my_app_bar);
     ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
     return v;
}
Alexandr Svetenco
  • 171
  • 1
  • 2
  • 10
0

May be you need to,

((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle();

These 2 links will be helpful for you, Set up toolbar as actionbar in fragment

How to get Toolbar from fragment?

Hope this helps.

Community
  • 1
  • 1
Neh
  • 442
  • 4
  • 7