问题
I'm new to Android Studio and I'm having many problems doing a menubar. I have searched for many solutions but they weren't going right.
I tried this but I don't know what to do next:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
//Inflate the menu; this adds item to the action
//bar if its present
getMenuInflater().inflate(R.menu.my_context_menu, menu);
String title = "Item Three";
int groupId = Menu.NONE;
int itemID = MENU_ITEM;
int order = 103;
menu.add(groupId, itemId, order, title);
return true;
}
回答1:
First create a main_menu.xml file in your menu rescource folder (or any other...) :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/one"
android:title="Button 1"/>
<item android:id="@+id/two"
android:title="Button 2"/>
</menu>
Then
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.one:
// do something
return true;
case R.id.two:
//do something
return true;
default:
return super.onOptionsItemSelected(item);
}
}
来源:https://stackoverflow.com/questions/36940981/menu-bar-in-android-studio-project