Add MenuItem to ActionBarCompat using Java

We are going to add MenuItem, menuItem_Info, to ActionBarCompat using Java code.

With new menuItem_Info
New MenuItem of menuItem_Info added using Java code
Modify exercise from last exercise "Example of using ActionBarCompat with android-support-v7-appcompat".

To add new MenuItem dynamically, we have to assign new id to it. Create a new file, /res/values/ids.xml, to define our of ID:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="menuid_info" type="id"/>
</resources>


Modify onCreateOptionsMenu() method in MainActivity.java to add new MenuItem using Java code:
package com.example.testactionbarcompat;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

@Override
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.main, menu);

//add MenuItem(s) to ActionBar using Java code
MenuItem menuItem_Info = menu.add(0, R.id.menuid_info, 0, "Info");
menuItem_Info.setIcon(android.R.drawable.ic_menu_info_details);
MenuItemCompat.setShowAsAction(menuItem_Info,
MenuItem.SHOW_AS_ACTION_IF_ROOM|MenuItem.SHOW_AS_ACTION_WITH_TEXT);

return true;
}

}

download filesDownload the files.



Visit: ActionBarCompat Step-by-step