My android learning experience 33 and android learning experience 33
Add menu in Activity
1. Create a folder menu under the res directory
Right-click res and choose new> Folder. Set Folder name to menu.
2. Create an xml file under the newly created menu directory
Right-click menu, click new-> Android XML File, enter a name in the pop-up box, such as main, and click Finish.
3. Write the required menu item in the new main. xml file as follows:
1 <?xml version="1.0" encoding="utf-8"?>2 <menu xmlns:android="http://schemas.android.com/apk/res/android" >3 <item android:id="@+id/add_item"4 android:title="Add"/>5 <item android:id="@+id/remove_item"6 android:title="Remove"/>7 </menu>
4. The primary activity is returned.
Override two methods: onCreateOptionsMenu (Menu menu) and onOptionsItemSelected (MenuItem item );
The first is to add a menu, and the second is to respond to the event when the corresponding menu item is clicked.
public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.add_item: Toast.makeText(this, "ADD", Toast.LENGTH_SHORT).show(); break; case R.id.remove_item: Toast.makeText(this, "REMOVE", Toast.LENGTH_SHORT).show(); break; default: break; } return true; }
5. Running Effect