Lab4 #2 Add Option Menu Items to Your App


Android Option Menu Items to Your App


#1 Create a Menu folder

Right-clicked on res folder> New> Folder> Res folder

#2 Create a Menu resource file menu_main.xml


menu_main.xml
Type the followings in the xml file
It contains three items as show below. It will create 3 items automatically inside the res/menu directory.


<?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"
    xmlns:tools="http://schemas.android.com/tools">

    <item  android:id="@+id/item1"
        android:title="Item 1"/>
    <item  android:id="@+id/item2"
        android:title="Item 2"/>
    <item  android:id="@+id/item3"
        android:title="Item 3"
        app:showAsAction="withText"/>
</menu>

 At the File: MainActivity.java
ADD in these 2 blocks of codes for method
public boolean onCreateOptionsMenu(Menu menu) :  Add menu item to action bar
and

public boolean onOptionsItemSelected(MenuItem item):  like listener to react to the item selected from menu

 
  
  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) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.menu_main, menu);  
        return true;  
    }  
  
    @Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
       int id = item.getItemId();  
        switch (id){  
            case R.id.item1:  
                Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();  
                return true;  
            case R.id.item2:  
                Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();  
                return true;  
            case R.id.item3:  
                Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show();  
                return true;  
            default:  
                return super.onOptionsItemSelected(item);  
        }  
    }  }  



Use ALT+Enter to import class for Menu,  MenuItem and  Toast






















Goto Build>Rebuild Project

Run>Run App

See your emulator




Expected Output





Demo and explanation of codes

No comments:

Post a Comment

Note: only a member of this blog may post a comment.