B
B
bvitaliyg2013-05-12 16:36:36
Android
bvitaliyg, 2013-05-12 16:36:36

When running a fragment, is onCreateOptionsMenu() called twice?

There is a simple application built on fragments. When changing a fragment, a menu should be created using the ActionBar:

class BaseFragment extends Fragment {

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle clicks
        return true;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Create a menu
        super.onCreateOptionsMenu(menu, inflater);
    }
}

Code that starts the snippet:
public void startFragment(BaseFragment fragment) {
    getSupportFragmentManager()
    .beginTransaction()
    .replace(android.R.id.content, fragment)
    .commit();
}

The problem is that onCreateOptionsMenu() is called twice in the starting fragment - the first time, as indicated, during onCreate(), but the second time after onResume() is called. Moreover, when the very first fragment in order is launched, everything works fine, but after it this error already begins.
Of the libraries for the purity of the experiment, I left only SupportLibrary.
I can assume that the source of the problem is in the startFragment() method, because replace() is called there and the error occurs after the first run. But I really need to replace fragments in android.R.id.content.
How could the problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
futurelink, 2013-05-15
@futurelink

First you need to try this, I think it will help:

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

I used exactly this method of replacing a fragment, just this way. Everything worked great.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question