Search code examples
javaandroidxmlappbar

How to display app bar (menu) xml file


I am trying to find a way to display a menu xml file in my App bar and I got stuck so I am asking for help.

This is what I have got so far:

main activity xml:

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

main activity java:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

}

and a xml file in the menu folder.

At the moment the only thing that is being displayed in the App Bar is the app name.(there should be also a settings item that is not being displayed)

Do I have to reverence somewhere where the xml file is or do I have to edit another xml file? Or do am I missing something completely?

I followed the steps in this guide: https://developer.android.com/training/appbar/setting-up.html

If you need any information that I am missing please ask. Thank You for your help.


Solution

  • I forgot to add something like that:

        @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_activity_actions, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
    
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }