java setContentView(R.layout.activity_main) vs getMenuInflater().inflate(R.menu.activity_main, menu)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14163466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:18:20  来源:igfitidea点击:

setContentView(R.layout.activity_main) vs getMenuInflater().inflate(R.menu.activity_main, menu)

javaandroidinflate

提问by FRR

Why do I have to tell my activity what its layout should be twice?

为什么我必须两次告诉我的活动它的布局应该是什么?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // <--
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu); // <--
    return true;
}

What's the difference between these two methods?. when should I use one, and when the other?

这两种方法有什么区别?我什么时候应该使用一个,什么时候使用另一个?

回答by A--C

They are two separate things. The names tell you. R.layout.activity_mainis your layout, R.menu.activity_mainis for your menu.

它们是两个不同的东西。名字告诉你。R.layout.activity_main是你的布局,R.menu.activity_main是你的菜单

setContentView()sets the layout for the Activity. It includes Buttons, TextViews, etc.

setContentView()设置活动的布局。它包括按钮、文本视图等。

onCreateOptionsMenu()makes the menu that you see when you press the menu key or it populates the ActionBar on Android 3.0+.

onCreateOptionsMenu()使您在按下菜单键时看到的菜单或它填充 Android 3.0+ 上的 ActionBar。

They do two completetly separate things. setContentView()is often needed (unless you have an empty Activity), onCreateOptionsMenu()is optional, depending on if you need to show more options.

他们做两件完全不同的事情。setContentView()通常需要(除非您有一个空的Activity),onCreateOptionsMenu()是可选的,取决于您是否需要显示更多选项。

回答by satti

java file inside the gen folder there will be defined layout, ID and menu static class. you will get the idea from there.

gen 文件夹内的 java 文件将定义布局、ID 和菜单静态类。你会从那里得到想法。