How can I change option menu in different fragments?
Put setHasOptionsMenu(true)
in constructor and inflate fragment specific menu.
public class FragmentA extends Fragment {
public FragmentA() {
setHasOptionsMenu(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragmenta_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
menu in main activity
public class MainActivity extends Activity {
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
Can all be done via Fragment - no need to inflate menu from activity:
public class UpdateFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.update_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.navUpdateProfile:
showToast("navUpdateProfile");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}