toolbar menu item click in fragments
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!
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;
}
@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);
}