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

StackOverflow https://stackoverflow.com/questions/14163466

  •  13-01-2022
  •  | 
  •  

Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top