New MenuItem of menuItem_Info added using Java code |
To add new MenuItem dynamically, we have to assign new id to it. Create a new file, /res/values/ids.xml, to define our
<?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 the files.
Visit: ActionBarCompat Step-by-step
0 comments:
Post a Comment