create new menuInflater or getMenuInflater() from activity?

半世苍凉 提交于 2019-11-30 13:07:28

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.

You should use MenuInflater instance that is passed to the method public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) (notice the 2nd argument)
There's no real difference, because normally you will "forget" it as soon as you finish using it, but why would you need to create one if you already have one from the arguments?

Kapil Bansal

Change from this :

MenuInflater inflater = getMenuInflater();

To this:

MenuInflater inflater = getActivity().getMenuInflater();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!