2

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?

Foggzie
  • 9,691
  • 1
  • 31
  • 48
frankelot
  • 13,666
  • 16
  • 54
  • 89

2 Answers2

9

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.

A--C
  • 36,351
  • 10
  • 106
  • 92
  • I see. and by "menu" you mean this -> https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrVPCPADkO2xtE_33ELya-evX_fEmXPJZ3n3TnOm-PdY38zGiEIw ? – frankelot Jan 04 '13 at 19:27
  • However, when you create a Fragment, you DO Use the inflater. how come?. why can't I use setContentView for those as well? – frankelot Jan 04 '13 at 19:32
  • You're talking about `getView()` in fragments. That's because Fragments don't have a `setContentView()` method. However note that it doesn't use `getMenuInflater()`, but instead a `LayoutInflater`. Both inflate, but `LayoutInflater` is for layouts. – A--C Jan 04 '13 at 19:36
  • Okay, I think I got it.. Thanks. I'm just picking up Android programming and it's pretty confusing so far. I really appreciate it!. – frankelot Jan 04 '13 at 19:39
  • @user1949554: no problem! if you could check the hollow checkmark besides my answer (to accept this answer) it would be appreciated :) – A--C Jan 04 '13 at 19:42
0

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

satti
  • 11
  • 2