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

frankelot picture frankelot · Jan 4, 2013 · Viewed 17k times · Source

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?

Answer

A--C picture A--C · Jan 4, 2013

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.