I'm creating new option menu inside fragment but after reading http://developer.android.com/resources/articles/avoiding-memory-leaks.html which said to it's better to use context-application than context-activity, I'm afraid to use getActivity().getMenuInflater()
So, actually which one better
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuInflater mInflater = new MenuInflater(getActivity().getApplicationContext());
mInflater.inflate(R.menu.simple_menu, menu);
}
Or the one call activity
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuInflater mInflater = getActivity().getMenuInflater();
mInflater.inflate(R.menu.simple_menu, menu);
}
and, what's the differences between the two of 'em? or..both are just the same?
Thanks.
You use it to get a MenuInflater . A MenuInflater can "inflate" menu resources, converting the XML representation into a tree of Menu and MenuItem objects. In turn, those objects are used to populate things like the action bar and Toolbar widgets.
Stay organized with collections Save and categorize content based on your preferences. This class is used to instantiate menu XML files into Menu objects. For performance reasons, menu inflation relies heavily on pre-processing of XML files that is done at build time.
Find the onCreateOptionsMenu(Menu menu) method which needs to override in Activity class. This creates menu and returns Boolean value. inflate inflates a menu hierarchy from XML resource. public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().
They are very similar. Looking through the MenuInflator's source, the only thing it uses the context for is to access the resource files. So the specific context doesn't matter to the MenuInflator.
As for memory leaks, the article you reference says
The most obvious [way to avoid memory leaks] is to avoid escaping the context outside of its own scope
Unless you pass the MenuInflator (or Menu) to another class then it is contained in the activity and won't be leaked.
EDIT
In addition Activity.getMenuInflator()
is just a convenience method for new MenuInflator()
. In fact this is the method inside the Activity class:
public MenuInflater getMenuInflater() {
return new MenuInflater(this);
}
It is usually better to use convenience methods since they allow for the underlying implementation to change in future versions without you having to change your code. For example if the above method is modified to return a cached instance instead of creating a new one each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With