Working with Menu and Action Bar
Working with Menu Through XML Files, Java code
Working with Menu Group
Add Event Listener to menu item
Using intent in Menu Item
Working with Sub Menu, Context Menu, Popup Menu, Dynamic Menu
/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.trankyphat.app.androidmenus.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewId" android:text="Long touch in here to show context menu" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewPopupMenu" android:text="Popup Menu Show in here" /> </LinearLayout>
/res/menu/my_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:id="@+id/menuGroup_Main"> <item android:id="@+id/menu_item1" android:orderInCategory="1" android:title="item1 text" /> <item android:id="@+id/menu_item2" android:orderInCategory="2" android:enabled="true" android:icon="@drawable/ic_action_android" android:title="item2 text" /> <item android:id="@+id/menu_item3" android:orderInCategory="3" android:title="item3 text" /> <!--<item android:id="... " android:onClick="a-method-name-in-your-activity" ... </item>--> </group> </menu>
/res/menu/popup_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <!-- This group uses the default category. --> <group android:id="@+id/menuGroup_Popup"> <item android:id="@+id/popup_menu_1" android:title="Menu 1" /> <item android:id="@+id/popup_menu_2" android:title="Menu 2" /> </group> </menu>
MainActivity.java
package com.trankyphat.app.androidmenus; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.PopupMenu; import android.widget.TextView; 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); //Create Menu with XML file //CreateMenuWithXML(menu); //Create Menu with Java code //CreateMenuWithJavaCode(menu); //Working with menu group WorkingWithGroupMenuAndRespondingToMenuItemThroughListeners(menu); //addSubMenu(menu); //Add context menu TextView tv = (TextView)this.findViewById(R.id.textViewId); registerForContextMenu(tv); //Add Popup menu to Textview showPopupMenu(); //It is important to return true to see the menu return true; } //Respond to menus by overriding onOptionsItemSelected(); //Method 1 @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i("MyMessage", "Click on MenuItem Id: " + Integer.toString(item.getItemId())); if (item.getItemId() == R.id.menu_item1) { //do something //for items handled Log.i("MyMessage", "Click on Menu item 1"); //Invoke Intent IntentsUtils.invokeWebSearch(this); return true; } else if (item.getItemId() == R.id.menu_item2) { //do something Log.i("MyMessage", "Click on Menu item 2"); return true; } else if (item.getItemId() == R.id.menu_item3) { //do something Log.i("MyMessage", "Click on Menu item 3"); return true; } return super.onOptionsItemSelected(item); } //Create dynamic menu //Change menu item before display in here @Override public boolean onPrepareOptionsMenu(Menu menu) { //disable first menu item menu.getItem(0).setEnabled(false); return super.onPrepareOptionsMenu(menu); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { //v.getId() . Check Id of view, if create multi context menu in one activity menu.setHeaderTitle("Sample Context Menu"); menu.add(200, 200, 200, "item1"); } @Override public boolean onContextItemSelected(MenuItem item) { Log.i("MyMesage", "On click context menu with id: " + item.getItemId()); if (item.getItemId() == 200) { //handle this menu item return true; } return super.onContextItemSelected(item); } private void CreateMenuWithXML(Menu menu){ MenuInflater inflater = getMenuInflater(); //from activity inflater.inflate(R.menu.my_menu, menu); } private void CreateMenuWithJavaCode(Menu menu){ menu.add(0 // Group ,1 // item id ,0 //order ,"item1"); // title menu.add(0,2,1,"item2"); menu.add(0, 3, 2, "item3"); } private void WorkingWithGroupMenuAndRespondingToMenuItemThroughListeners(Menu menu){ //Group 1 int group1 = 1; MenuItem menuGroup1Item1 = menu.add(group1,1,1,"g1.item1"); MenuItem menuGroup1Item2 = menu.add(group1, 2, 2, "g1.item2"); //Group 2 int group2 = 2; MenuItem menuGroup2Item1 = menu.add(group2,3,3,"g2.item1"); MenuItem menuGroup2Item2 = menu.add(group2,4,4,"g2.item2"); //Using listener as a callback for MenuItem click //Method 2 //Method 2 is priority than override onOptionsItemSelected MyMenuItemResponse myResponse = new MyMenuItemResponse(); //menuGroup1Item1.setOnMenuItemClickListener(myResponse); menuGroup1Item2.setOnMenuItemClickListener(myResponse); menuGroup2Item1.setOnMenuItemClickListener(myResponse); menuGroup2Item2.setOnMenuItemClickListener(myResponse); //Set Intent: don't set response before, response is priority than intent Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.google.com")); menuGroup1Item1.setIntent(intent); //Android 3.0+ not showing icon //Set icon for menu group 1 item 2 menuGroup1Item2.setIcon(R.drawable.ic_action_emo_cool); //menu.getItem(0).setIcon(R.drawable.ic_action_emo_cool); } private void addSubMenu(Menu menu){ //Secondary items are shown just like everything else int base=Menu.FIRST + 100; SubMenu sm = menu.addSubMenu(base,base+1,Menu.NONE,"submenu"); sm.add(base,base+2,base+2,"sub item1"); sm.add(base,base+3,base+3,"sub item2"); sm.add(base,base+4,base+4,"sub item3"); //the following is ok //submenus do not support icon menu items sm.setIcon(R.drawable.ic_action_android); //This will result in runtime exception //Cannot add sub menu to another submenu else //sm.addSubMenu("try this"); } //Invoke the following method to show a popup menu private void showPopupMenu() { //Get hold of a view to anchor the popup TextView tv = (TextView)findViewById(R.id.textViewPopupMenu); //instantiate a popup menu. var "this" stands for activity PopupMenu popup = new PopupMenu(this, tv); //the following code for 3.0 sdk //popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu()); //Or in sdk 4.0 and above popup.inflate(R.menu.popup_menu); //Only use below to click callback popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { //do something here Log.i("MyMessage","Click on Popup Menu"); return true; } } ); popup.show(); } }
IntentsUtils.java
package com.trankyphat.app.androidmenus; import android.app.Activity; import android.content.Intent; import android.net.Uri; /** * Created by trank on 2/10/2016. */ public class IntentsUtils { public static void invokeWebBrowser(Activity activity) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.google.com")); activity.startActivity(intent); } public static void invokeWebSearch(Activity activity) { Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.setData(Uri.parse("http://www.google.com")); activity.startActivity(intent); } public static void dial(Activity activity) { Intent intent = new Intent(Intent.ACTION_DIAL); activity.startActivity(intent); } public static void call(Activity activity) { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:904-905-5646")); activity.startActivity(intent); } public static void showMapAtLatLong(Activity activity) { Intent intent = new Intent(Intent.ACTION_VIEW); //geo:lat,long?z=zoomlevel&q=question-string intent.setData(Uri.parse("geo:0,0?z=4&q=business+near+city")); activity.startActivity(intent); } public static void invokeBaseView(Activity activity) { Intent intent = new Intent("com.androidbook.intent.action.ShowBasicView"); activity.startActivity(intent); } public static void tryOneOfThese(Activity activity) { //IntentsUtils.call(activity); IntentsUtils.invokeBaseView(activity); } }
MyMenuItemResponse.java
package com.trankyphat.app.androidmenus; import android.util.Log; import android.view.MenuItem; /** * Created by trank on 2/10/2016. */ public class MyMenuItemResponse implements MenuItem.OnMenuItemClickListener { public MyMenuItemResponse(){ } @Override public boolean onMenuItemClick(MenuItem item) { Log.i("MyMessage", "Response With Listener - Click on menu item with id: " + Integer.toString(item.getItemId())); return true; } }
Action Bars
Introduced in Android 3.0 and expanded in Android 4.0, an ActionBar extends the reach of menus into the title bar of an activity. This allows frequently used actions easily available to the user without searching through option menus or context menus. In addition to icons and menu items, an action bar can accommodate other views such as tabs, or a list, or a search box to help with navigation
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.trankyphat.app.exploreactionbars.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </RelativeLayout>
tool_bar.xml
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark" android:elevation="4dp" > </Toolbar>
MainActivity.java
package com.trankyphat.app.exploreactionbars; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.widget.Toolbar; public class MainActivity extends AppCompatActivity { private LayoutInflater mInflater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //ActionBar bar = this.getActionBar(); //bar.setTitle("Some title of your choosing"); mInflater = LayoutInflater.from(this); Toolbar toolbar = (Toolbar)mInflater.inflate(R.layout.tool_bar, null);// Attaching the layout to the toolbar object setActionBar(toolbar);// Setting toolbar as the ActionBar with setSupportActionBar() call //Set Action Bar Title this.getActionBar().setTitle("Some Title of ActionBar"); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); //from activity inflater.inflate(R.menu.menu, menu); return true; } }