I have a rare problem. I have an activity that has tabs populated dynamically (up to 20 tabs). Each fragment has an implementation of OnCreateOptionsMenu and a menu which contains a bookmark icon that changes color when pressed. There is a class variable menu of type Menu which is set when fragment's OnCreateOptionsMenu is called. This is to enable me set the bookmark menu item outside the onCreateOptionsMenu(This is also done dynamically).
Problem:
When the parent activity have only a single tab(One fragment instance), this implementation works fine. However with more than one tab, the app crashes with the error:
Attempt to invoke interface method android.view.MenuItem android.view.Menu.findItem(int)
What I think: I think the problem is that the OnCreateOptionsMenu is called once i.e Class variable: menu is set only once for the first tab (fragment) hence when other tabs are added, menu is null
Some codes: Fragment
Menu menu;
...
...
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setMenuBookmark(ques_obj);
}
private void setMenuBookmark(QuestionAnswerList ques_obj){
MenuItem menuBookmark = this.menu.findItem(R.id.action_bookmark);
if (ques_obj.getIs_bookmarked().equals("1")) {
menuBookmark.setIcon(R.drawable.ic_bookmark_white_24dp);
} else {
menuBookmark.setIcon(R.drawable.ic_bookmark_border_white_24dp);
}
}
...
...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.cbt_fragment_menu, menu);
this.menu = menu;
super.onCreateOptionsMenu(menu, inflater);
}
P.S setHasOptionsMenu() is set to true in Fragment's OnCreate
Try this way