简体   繁体   中英

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

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?

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

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM