Sunday, December 15, 2013

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"?>
    <item name="menuid_info" type="id"/>

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

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        //add MenuItem(s) to ActionBar using Java code
        MenuItem menuItem_Info = menu.add(0,, 0, "Info");
        return true;

download filesDownload the files.

Visit: ActionBarCompat Step-by-step

No comments: