I'm using a menu for the actionbar, and here is my xml mainactivity.xml under menus:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id = "@+id/Viewmain"
android:orderInCategory="200"
app:showAsAction="always"
android:title="VIEW"/>
<item
android:id = "@+id/Addmain"
android:orderInCategory="205"
app:showAsAction="always"
android:title="ADD"/>
</menu>
Here is the code I used to navigate the buttons on the actionbar to other Activities in mainactivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onContextItemSelected (MenuItem item)
{
if (item.getItemId()==200)
{
Intent myintent = new Intent(this, ViewStats.class );
startActivity(myintent);
return true;
}
else if (item.getItemId()==205)
{
Intent myaddintent = new Intent(this,Sales.class );
startActivity(myaddintent);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
this.myMenu = menu;
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
However when I click on the actionbar buttons "VIEW" & "ADD", no changes occur. What is wrong with my codes? Please help. (Note: No errors were shown on the stacktrace)
you have to implement following methods to options menu
for creating menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);///here add your menu layout
return true;
}
for select menu item this method need to implemented
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
don't add hard coded id comparison u can just add ur item id by R.id.yourid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.