I know this question has been asked and but I am unable to solve my problem after looking at those answer. I have an Activity with a Fragment. In fragment, I have added the
From Android Docs, for Fragment
:
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu. For this method to be called, you must have first called setHasOptionsMenu(boolean).
so you want to control actionbar menu in Fragment, then you have to call setHasOptionsMenu
method better in Fragment's onCreate(...)
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
also important is that you should not use inflateMenu
and onCreateOptionsMenu
both together for same ToolBar
, inflateMenu
is for standalone without setting ToolBar
as ActionBar
.
Suggestion:
keep one ToolBar
in Activity
as ActionBar
for your App, and another ToolBar
standalone inside Fragment
.
Hope this help!
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.training1_fragment, container,
false);
setHasOptionMenu(true);
return v;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save :
{
//Write here what to do you on click
return true;
}
}
return super.onOptionsItemSelected(item);
}
You should getPointer toolbar from your activity class and inflate menu in fragment class.
You can look this ex:
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
activity = ((DescriptionActivity ) getActivity());
Toolbar tollbar=getView.findViewById(R.id.your_toolbar);
activity.setSupportActionBar(toolbar);
activity.toolbar.inflateMenu(R.menu.menu_search);
activity.toolbar.setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_search:
break;
}
return false;
}
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MyFragment extends Fragment implements Toolbar.OnMenuItemClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
Toolbar toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(this);
return rootView;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_menu:
//do sth here
return true;
}
return false;
}