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.