Cdacians

Cdacians
Cdacians

Sunday 21 April 2013

Android’s PopupMenu class


Working with Android’s PopupMenu class

Takeaway: Android’s PopupMenu widget takes all of the heavy lifting out of adding popup-like menu functionality in your apps. Here are the basics about PopupMenu.
On the Android operating system over the last several years, we have seen major overhauls in user interface (UI) and user experience. One pattern that has emerged and taken hold is the quick action or popup menu.  These menus appear in context and can be attached to any view in your hierarchy in a non-intrusive manner.
Prior to Honeycomb, achieving a popup-like menu functionality inside your apps was quite a bit of work, but now the thoughtful folks on Google’s Android framework team have built a PopupMenu widget right into the UI kit that does all the heavy lifting. This tutorial will walk you through the basics of PopupMenu. Feel free to follow along with the step-by-step tutorial below or download and import the entire project into Eclipse.
1. Create a new Android project in Eclipse. The PopupMenu class requires you to target API level 11 or greater. Be sure to rename your startup activity to Main.java and the associate layout to main.xml.
2. In the /res/layout folder, modify main.xml. We will use a linear layout with a series of vertically stacked text views.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="20sp"
        android:textColor="#000000"
        android:layout_margin="20dip"
        android:text="Popup Menu Example" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Touch here to see the menu."
        android:layout_margin="20dip"
        android:layout_gravity="center"
        android:textColor="#0000ff"
        android:id="@+id/anchor"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
        android:layout_gravity="center"
        android:textSize="40sp"
        android:textColor="#808080"
        android:id="@+id/selection"/>
</LinearLayout>
3. Next we will work with Main.java in the /src folder. The main class extends activity and implements both an on click listener and the on menu item click listener. In the on create override we create a new menu and wire it up. The popup menu class is based on the common menu item entity, so if you’ve used context menus or standard menus it should look familiar.
Main.java
package com.authorwjf.popmenu;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.app.Activity;
public class Main extends Activity implements OnClickListener, OnMenuItemClickListener
{

       private PopupMenu popupMenu;
       private final static int ONE = 1;
       private final static int TWO = 2;
       private final static int THREE = 3;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             popupMenu = new PopupMenu(this, findViewById(R.id.anchor));
             popupMenu.getMenu().add(Menu.NONE, ONE, Menu.NONE, "Item 1");
             popupMenu.getMenu().add(Menu.NONE, TWO, Menu.NONE, "Item 2");
             popupMenu.getMenu().add(Menu.NONE, THREE, Menu.NONE, "Item 3");
             popupMenu.setOnMenuItemClickListener(this);
             findViewById(R.id.anchor).setOnClickListener(this);
       }
}
4. In our on click handler we only need to show the popup menu. Android will take care of deciding whether to toggle the menu on or off, as well as lay it out on the screen so it does not obscure the view that acts as its anchor.
@Override
public void onClick(View v) {
       popupMenu.show();
}
5. We want to update our display showing which item is selected using the appropriate callback.
@Override
public boolean onMenuItemClick(MenuItem item) {
       TextView tv = (TextView) findViewById(R.id.selection);
       switch (item.getItemId()) {
       case ONE:
              tv.setText("ONE");
              break;
       case TWO:
              tv.setText("TWO");
              break;
       case THREE:
              tv.setText("THREE");
              break;
       }
       return false;
}
There we have it — a simple but elegant widget you can employ to enhance your applications. Load the sample code to a device or emulator and give it a try. Remember, the target needs to be running Honeycomb or better.
Figure A
Figure B
Figure C
Thanks
akm
cdacians

PopUpWindow in Android


PopUpWindow in Android

Android supports Popup Window like in IPhone. The difference between pop up window and dialog is we have to set the position (like center, top, bottom...) and also x and y positions. The below snippets explains the way.
 Home.java:
package com.popup.activities;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;

public class Home extends Activity
{
    private Button btnShowPopUp;
    private PopupWindow mpopup;
       
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnShowPopUp = (Button)findViewById(R.id.btnShowPopUp);
       
        btnShowPopUp.setOnClickListener(new OnClickListener()
        {           
            @Override
            public void onClick(View arg0)
            {
                View popUpView = getLayoutInflater().inflate(R.layout.popup, null); // inflating popup layout
                mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true); //Creation of popup
                mpopup.setAnimationStyle(android.R.style.Animation_Dialog);  
                mpopup.showAtLocation(popUpView, Gravity.BOTTOM, 0, 0);    // Displaying popup
               
                Button btnOk = (Button)popUpView.findViewById(R.id.btnOk);
                btnOk.setOnClickListener(new OnClickListener()
                {                   
                    @Override
                    public void onClick(View v)
                    {
                        mpopup.dismiss();  //dismissing the popup
                    }
                });
               
                Button btnCancel = (Button)popUpView.findViewById(R.id.btnCancel);
                btnCancel.setOnClickListener(new OnClickListener()
                {                   
                    @Override
                    public void onClick(View v)
                    {
                        mpopup.dismiss(); dismissing the popup
                    }
                });
            }
        }); 
    }
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  
    <Button
        android:layout_width="wrap_content"
        android:id="@+id/btnShowPopUp"
        android:text="ShowPopUp"
        android:layout_height="wrap_content">
    </Button>
  
</LinearLayout>
popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:orientation="vertical"
  android:background="#90FFFFFF"
  android:layout_height="wrap_content">
 
  <TextView
      android:layout_width="fill_parent"
      android:text="PopUp Window"
      android:textColor="#000000"
      android:gravity="center"
      android:textStyle="bold"
      android:layout_height="wrap_content">
  </TextView>
 
  <Button
      android:layout_width="fill_parent"
      android:id="@+id/btnOk"
      android:text="Ok"
      android:layout_height="wrap_content">
  </Button>
 
  <Button
      android:layout_width="fill_parent"
      android:id="@+id/btnCancel"
      android:text="Cancel"
      android:layout_height="wrap_content">
  </Button>
 
</LinearLayout>


Thanks
akm
cdacians

Android Context Menus


Android Context Menus

  • Share
Context menus are invoked in android when user performs a long click ( click and hold). While theOptions menu is associated with a specific activity, context menus are associated with specific views within the activity. Thus an activity can have only one options menu but many context menus.

Context Menu Creation

To create a context menu, you need to:
  • Register the view element to use a Context menu using the registerForContextMenu (View v)
  • Override the onCreateContextMenu ()method.  The method takes 3 arguments:
    • A default ContextMenu object,
    • The view element for which the context menu is desired and
    • A ContextMenuInfo object that can be used to pass any additional information that can used for  creation of the Context Menu.

Responding to Context menu Selections

To respond to context menus override the onContextItemSelected ()  method . The menu item that was selected is passed in as a argument to this method.

Example

Lets look at the context menu usage with a simple example.  In this example we have an activity with two TextView elements,  one with the context menu and the other without. The context menu lets us choose the background color of the TextView element as shown in the  sample screenshot below.
Android Context Menu Demo

Context Menu Definition

Menus are also resources in android. To define a menu create a file called “color_menu.xml” and place it under res/menu folder.  As shown below, you define the menu inside the menu tag and populate the menu items using the item tag. You need to specify a valid id for each menu item. This is used to respond to menu item selections as shown later below.
?
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
    <item android:id="@+id/menu_red" android:title="Red" />
    <item android:id="@+id/menu_green" android:title="Green"/>
    <item android:id="@+id/menu_blue" android:title="Blue"/>
</menu>

Activity Layout Definition

The activity layout is simple and consists of a linear layout with two TextView elements within it as shown.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
 
    <TextView android:id="@+id/context_color"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent"
              android:gravity="center"
              android:layout_margin="5dip"
              android:textColor="@color/DarkGrey"
              android:text="Color Context Menu ( Click and Hold)"
            />
 
    <TextView android:id="@+id/menuDemoDiv1"
                 android:layout_height="1dip"
                 android:layout_width="match_parent"
                 android:background="@color/white"
                 android:textColor="@color/DarkGrey"
                 android:text=""/>
 
    <TextView android:id="@+id/menu_textView2"
                  android:layout_height="wrap_content"
                  android:layout_width="fill_parent"
                  android:gravity="center"
                  android:layout_margin="5dip"
                  android:textColor="@color/DarkGrey"
                  android:text="TextView with no context Menu"
                />
</LinearLayout>

Java Source Code

  • Register the first TextView element to use the ContextMenu within the onCreate() method of the activity
  • Override the onCreateContextMenu() method to create the context menu. The general pattern is to use the id of the view element to generate different menus.  In this case we delegate the menu creation to a private helper method. This method uses the MenuInflater instance available to the activity to inflate the color menu defined as a xml resource. Just as with layout files, android automatically generate unique ids for the menu resources based on the name of the file which is then passed into the getMenuInflater (). inflate ()method.
  • You can respond to the menu selections by switching on the id of  the MenuItem being passed as argument to the onContextItemSelected () method. In this case we change the background color of the TextView element based on the selection.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class MenuDemo extends Activity {
   private TextView m_contextColor;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.menudemo);
      m_contextColor = (TextView) findViewById(R.id.context_color);
      /**
       * Register the View elements in the activity to generate
       * Context menus
       */
      registerForContextMenu(m_contextColor);
   }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                            ContextMenu.ContextMenuInfo menuInfo) {
       switch (v.getId()) {
          case R.id.context_color:
             createMenu(R.menu.color_menu, menu, "Choose a color");
             break;
          default:
             super.onCreateContextMenu(menu, v, menuInfo);
       }
    }
   private void createMenu(int menuID, ContextMenu menu,
                                            String title) {
      /**
       * Use a MenuInflater associated with the activity to
       * inflate the Menu layout
       */
      getMenuInflater().inflate(menuID, menu);
      menu.setHeaderTitle(title);
   }
 
   @Override
   public boolean onContextItemSelected(MenuItem item) {
      switch (item.getItemId()) {
         case R.id.menu_red:
            m_contextColor.setBackgroundResource(R.color.LightRed);
            return true;
         case R.id.menu_blue:
            m_contextColor.setBackgroundResource(R.color.DullBlue);
            return true;
         case R.id.menu_green:
            m_contextColor.setBackgroundResource(R.color.LightGreen);
            return true;
         default:
            return super.onContextItemSelected(item);
      }
   }
}

Happy Coding !!!
akm
cdacians