Tuesday, 3 May 2016

Android Menu

Here, you will learn about the option menu that is primary menu, context menu that works on long press and popup menu.


  • Option Menu
  • Context Menu
  • Popup Menu

1. Android Option Menu Example




Android Option Menus are the primary menus of android. They can be used for settings, search, delete item etc.



Here, we are going to see two examples of option menus. First, the simple option menus and second, options menus with images.



Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To perform event handling on menu items, you need to override onOptionsItemSelected() method of Activity class.



Android Option Menu Example

Let's see how to create menu in android. Let's see the simple option menu example that contains three menu items.



activity_main.xml



 <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"   
   xmlns:tools="http://schemas.android.com/tools"   
   android:layout_width="match_parent"   
   android:layout_height="match_parent"   
   tools:context=".MainActivity" >   
    
   <TextView   
     android:layout_width="wrap_content"   
     android:layout_height="wrap_content"   
     android:text="@string/hello_world" />   
    
 </RelativeLayout>   

menu_main.xml

It contains three items as show below. It is created automatically inside the res/menu directory.

 <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >   
   <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"/>   
 </menu>   


MainActivity.java

This class displays the content of menu.xml file and performs event handling on clicking the menu items.

 package com.androidtutorialforum.optionmenu;   
 import android.os.Bundle;   
 import android.app.Activity;   
 import android.view.Menu;   
 import android.view.MenuItem;   
 import android.widget.Toast;   
 public class MainActivity extends Activity {   
   @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.main, menu);//Menu Resource, Menu   
     return true;   
   }   
   @Override   
   public boolean onOptionsItemSelected(MenuItem item) {   
     switch (item.getItemId()) {   
       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);   
     }   
   }   
 }   
   



2. Android Context Menu Example

Android context menu appears when user press long click on the element. It is also known as floating menu.

It doesn't support item shortcuts and icons.

Android Context Menu Example

Let's see the simple example of context menu in android.

activity_main.xml

Drag one listview from the pallete, now the xml file will look like this:

activity_main.xml
 <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=".MainActivity" >   
    
   <ListView   
     android:id="@+id/listView1"   
     android:layout_width="match_parent"   
     android:layout_height="wrap_content"   
     android:layout_alignParentLeft="true"   
     android:layout_alignParentTop="true"   
     android:layout_marginLeft="66dp"   
     android:layout_marginTop="53dp" >   
   </ListView>   
    
 </RelativeLayout>   

Activity class

Let's write the code to display the context menu on press of the listview.

MainActivity.java
 package com.androidtutorialforum.contextmenu;   
 import android.os.Bundle;   
 import android.app.Activity;   
 import android.view.ContextMenu;   
 import android.view.ContextMenu.ContextMenuInfo;   
 import android.view.Menu;   
 import android.view.MenuItem;   
 import android.view.View;   
 import android.widget.AdapterView;   
 import android.widget.ArrayAdapter;   
 import android.widget.ListView;   
 import android.widget.Toast;   
 public class MainActivity extends Activity {   
   ListView listView1;   
   String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};   
   @Override   
   protected void onCreate(Bundle savedInstanceState) {   
     super.onCreate(savedInstanceState);   
     setContentView(R.layout.activity_main);   
     listView1=(ListView)findViewById(R.id.listView1);   
     ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);   
     listView1.setAdapter(adapter);   
     // Register the ListView for Context menu   
     registerForContextMenu(listView1);   
   }   
   @Override    
   public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)   
   {   
       super.onCreateContextMenu(menu, v, menuInfo);   
       menu.setHeaderTitle("Select The Action");    
       menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title    
       menu.add(0, v.getId(), 0, "SMS");    
   }    
   @Override    
   public boolean onContextItemSelected(MenuItem item){    
       if(item.getTitle()=="Call"){   
         Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).show();   
       }    
       else if(item.getTitle()=="SMS"){   
         Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LONG).show();   
       }else{   
         return false;   
       }    
      return true;    
    }    
   }   







3. Android Popup Menu Example


Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu.



The android.widget.PopupMenu is the direct subclass of java.lang.Object class.


Android Popup Menu Example

Let's see how to create popup menu in android.

activity_main.xml

It contains only one button.

activity_main.xml
 <RelativeLayout xmlns:androclass="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=".MainActivity" >   
    
   <Button   
     android:id="@+id/button1"   
     android:layout_width="wrap_content"   
     android:layout_height="wrap_content"   
     android:layout_alignParentLeft="true"   
     android:layout_alignParentTop="true"   
     android:layout_marginLeft="62dp"   
     android:layout_marginTop="50dp"   
     android:text="Show Popup" />   
    
 </RelativeLayout>   


popup_menu.xml

It contains three items as show below. It is created inside the res/menu directory.

poupup_menu.xml
 <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >   
    
   <item   
     android:id="@+id/one"   
     android:title="One"/>   
      
   <item   
     android:id="@+id/two"   
     android:title="Two"/>   
       
   <item   
     android:id="@+id/three"   
     android:title="Three"/>   
        
 </menu>   

Activity class

It displays the popup menu on button click.

MainActivity.java
 package com.androidtutorialforum.popupmenu;   
 import android.os.Bundle;   
 import android.app.Activity;   
 import android.view.Menu;   
 import android.view.MenuItem;   
 import android.view.View;   
 import android.view.View.OnClickListener;   
 import android.widget.Button;   
 import android.widget.PopupMenu;   
 import android.widget.Toast;   
 public class MainActivity extends Activity {   
 Button button1;   
         
      @Override   
      protected void onCreate(Bundle savedInstanceState) {   
      super.onCreate(savedInstanceState);   
      setContentView(R.layout.activity_main);   
         
      button1 = (Button) findViewById(R.id.button1);   
      button1.setOnClickListener(new OnClickListener() {   
         
       @Override   
       public void onClick(View v) {   
       //Creating the instance of PopupMenu   
       PopupMenu popup = new PopupMenu(MainActivity.this, button1);   
       //Inflating the Popup using xml file   
       popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());   
         
       //registering popup with OnMenuItemClickListener   
       popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {   
        public boolean onMenuItemClick(MenuItem item) {   
        Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();   
        return true;   
        }   
       });   
    
       popup.show();//showing popup menu   
       }   
      });//closing the setOnClickListener method   
      }   
   }   











Fragment

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.

When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.


This document describes how to build your application to use fragments, including how fragments can maintain their state when added to the activity's back stack, share events with the activity and other fragments in the activity, contribute to the activity's action bar, and more.


Design Philosophy



Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.



For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity, side by side, and each fragment has its own set of lifecycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity, as illustrated in the tablet layout in figure 1.

You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behaviour with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when more than one cannot fit within the same activity.



Creating a Fragment

To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you're converting an existing Android application to use fragments, you might simply move code from your activity's callback methods into the respective callback methods of your fragment.

Usually, you should implement at least the following lifecycle methods:

Fragment Life Cycle

Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle.


onAttach()-The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.

onCreate()-The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

onCreateView()-The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

onActivityCreated()-The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object

onStart()-The onStart() method is called once the fragment gets visible.

onResume()-Fragment becomes active.

onPause()-The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.

onStop()-Fragment going to be stopped by calling onStop()

onDestroyView()-Fragment view will destroy after call this method

onDestroy()-onDestroy() called to do final clean up of the fragment's state but Not guaranteed to be called by the Android platform.


Note: There are also a few subclasses that you might want to extend, instead of the base Fragment class.

DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment.

ListFragment
Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.

PreferenceFragment
Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" activity for your application.

Adding a user interface

A fragment is usually used as part of an activity's user interface and contributes its own layout to the activity.

To provide a layout for a fragment, you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.

Note: If your fragment is a subclass of ListFragment, the default implementation returns a ListView from onCreateView(), so you don't need to implement it.

For example, here's a subclass of Fragment that loads a layout from the example_fragment.xml file:

 public static class ExampleFragment extends Fragment {  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container,  
                Bundle savedInstanceState) {  
     // Inflate the layout for this fragment  
     return inflater.inflate(R.layout.example_fragment, container, false);  
   }  
 }  

Adding a fragment to an activity

Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout.
  1. Declare the fragment inside the activity's layout file.
  2. Programmatically add the fragment to an existing ViewGroup

Declare the fragment inside the activity's layout file.

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="horizontal"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <fragment android:name="com.example.news.ArticleListFragment"  
       android:id="@+id/list"  
       android:layout_weight="1"  
       android:layout_width="0dp"  
       android:layout_height="match_parent" />  
   <fragment android:name="com.example.news.ArticleReaderFragment"  
       android:id="@+id/viewer"  
       android:layout_weight="2"  
       android:layout_width="0dp"  
       android:layout_height="match_parent" />  
 </LinearLayout>  



Programmatically add the fragment to an existing ViewGroup


At any time while your activity is running, you can add fragments to your activity layout. You simply need to specify a ViewGroup in which to place the fragment.
To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction. You can get an instance of FragmentTransaction from your Activity like this:

 // Create new fragment and transaction  
 Fragment newFragment = new ExampleFragment();  
 FragmentTransaction transaction = getFragmentManager().beginTransaction();  
   
 // Replace whatever is in the fragment_container view with this fragment,  
  transaction.replace(R.id.fragment_container, newFragment);  
    
 // Commit the transaction  
 transaction.commit();  


Source:
http://developer.android.com/guide/components/fragments.html