创建新menuInflater或getMenuInflater()的活动? [英] create new menuInflater or getMenuInflater() from activity?

查看:567
本文介绍了创建新menuInflater或getMenuInflater()的活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建内部片段,但看完之后新的选项菜单 <一href="http://developer.android.com/resources/articles/avoiding-memory-leaks.html">http://developer.android.com/resources/articles/avoiding-memory-leaks.html 它说这是更好地使用上下文的应用程序比上下文活动,我不敢用getActivity()。getMenuInflater()

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);

}

和,什么是两个'时间之间的区别? or..both是一样的?

and, what's the differences between the two of 'em? or..both are just the same?

感谢。

推荐答案

他们都非常相似。通过寻找MenuInflator的源,唯一它使用是访问资源文件的上下文。所以具体情况并不重要的MenuInflator。

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

除非你通过MenuInflator(或菜单)到另一个类则包含在活动并不会被泄露。

Unless you pass the MenuInflator (or Menu) to another class then it is contained in the activity and won't be leaked.

修改

此外 Activity.getMenuInflator()只是一个便捷方法新MenuInflator()。事实上,这是Activity类里面的方法:

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);
}

这是通常最好使用便利的方法,因为它们允许底层实现在未来的版本更改,恕不你无需改变你的code。例如,如果上述方法进行修改以返回创建一个新的每次的缓存实例,而不是

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.

这篇关于创建新menuInflater或getMenuInflater()的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆