Wednesday, June 3, 2015

Android Pop Up Menus

After finishing previous session on Option Menu, Context (Long Press) Menus. Lets see the most popular type of menu in android that is pop up menu. to handle some common functionality into applications we must use such type of menus.

These menus appear in context and can be attached to any view in your hierarchy in a non-intrusive manner. This tutorial will walk you through the basics of PopupMenu. Feel free to follow along with the step-by-step tutorial below.



       1. Create a new Android project in Eclipse. The PopupDemo class requires you to target API level 11 or greater. Be sure to rename your startup activity to PopupDemo.java and the associate layout to activity_popup_demo.xml.
     2. In activity_popup_demo.xml  I am adding one simple button so we can add click Listener on it. so popup menu will appear on same view.


activity_popup_demo.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:background="@drawable/main"
    tools:context=".PopupDemo" >

    <Button
        android:id="@+id/button1"
        android:layout_width="142dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
      
        android:background="@drawable/pop" />
  
</RelativeLayout>


Next we will work with PopupDemo.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.


PopupDemo.java
 


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
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 PopupDemo extends Activity {
Button p;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_popup_demo);
  p = (Button) findViewById(R.id.button1);
  p.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    //creating the instance of PopMenu class.
    PopupMenu pop = new PopupMenu(getApplicationContext(), p);
    //inflate the xml layout
    pop.getMenuInflater().inflate(R.menu.main, pop.getMenu());
    //registering popup OnMenuItemClickListener.
    pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
     
     @Override
     public boolean onMenuItemClick(MenuItem item) {
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(), " ur choice is "+item.getTitle(), Toast.LENGTH_LONG).show();
      return true;
     }
    });
    pop.show();//showing popup menu.
    
   }
  });
 }
 @Override
 public void onBackPressed() {
  Intent intent = new Intent(this, MainActivity.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
    | Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);
 }
 
}
 
Now, run this Application.
 

Stay tune for next session happy codding :)

Android Menus : Option Menu + Context Menu + PopUp Menu.

Hey guys!
Today we ‘re gonna see how to create a Menu with icon items, which on click, fire a respective to them message. What differentiates this article from other similars, is that we ‘re using the latest Android APIs, where Menus are manipulated differently.
Having created an Android project, using the latest platform, gives us by default a menu layout, as we can see:
 
For those who are more curious about what this contains, have a look at the Screen shots of this program:

 1. Option Menu.                                                                                                 2.Context Menu




 

 

 

 

 

 

 

 

 

 

menu.xml 

creating the menu item in menu.xml file 

<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"
    tools:context="com.allmenodemo.MainActivity" >

    <item
        android:id="@+id/home"
        android:orderInCategory="100"
        android:title="@string/home"
        android:icon="@drawable/home"
       />
     <item
        android:id="@+id/add"
        android:orderInCategory="100"
        android:title="@string/add"
         android:icon="@drawable/ic_action_add"
       />
      <item
        android:id="@+id/delete"
        android:orderInCategory="100"
        android:title="@string/delete"
         android:icon="@drawable/ic_delete"
        />
       <item
        android:id="@+id/logout"
        android:orderInCategory="100"
        android:title="@string/logout"
         android:icon="@drawable/logout"
        />

</menu>

Let’s pretend that we don’t really know anything about menus, so when running the app on our emulator, if we press the hardware “Menu” button, we should get something like Settings and more. 
here menu tag defines menu and item tag defines elements or items which will shown on option menu button.
Creating a custom menu in Android is very easy, Regarding an item, we actually need to define 3 properties:
  1. An id, which is useful to handle the action that we want our menu option to implement, when clicked. This can be done through a Java class.
  2. An icon, which has to lie under the drawable.
  3. A title, which is the displayed text in our menu item; this is about the title attribute we already know: it can be manipulated with both the “hardcoded” way and through the stored strings of our app.
lets move to the Java class for getting this things work.

before start up this code I must tell you one thing that I am implementing all types of android menu in separate section so please be careful while coping this code in your eclipse project. 

I am doing this class for :
  1. Option Menu.
  2. Context Menu.

MainActivity.java



package com.allmenudemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{
 //In this example I am creating both Menus: i.e. 
 //1.Option Menu.
 //2.Context Menu.
 
 ListView lv; 
//For context menu I am creating Simple ListView, So I can make 
//long press on item to get context menu.  
 String[] data = new String[] { "Message", "Call", "Email", "Note",
   "Meeting" };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  lv = (ListView) findViewById(R.id.listView1);

  ArrayAdapter ad = new ArrayAdapter(getApplicationContext(),
    android.R.layout.simple_list_item_1, data);
  lv.setAdapter(ad);
  registerForContextMenu(lv);

 }
 
 //Context Menu-------------------------------------
 @Override
 public void onCreateContextMenu(ContextMenu menu, View v,
   ContextMenuInfo menuInfo) {
  // TODO Auto-generated method stub
  menu.setHeaderTitle("Select Options");
  menu.add(0, v.getId(), 0, "Msg");
  menu.add(0, v.getId(), 0, "Call");
  menu.add(0, v.getId(), 0, "Email");
  menu.add(0, v.getId(), 0, "Note");
  menu.add(0, v.getId(), 0, "Meeting");

  super.onCreateContextMenu(menu, v, menuInfo);
 }
 @Override
 public boolean onContextItemSelected(MenuItem item) {
  // TODO Auto-generated method stub
  if (item.getTitle() == "Msg") {
   Intent i = new Intent(MainActivity.this, PopupDemo.class);
   startActivity(i);
   finish();
   Toast.makeText(getApplicationContext(), "U selected Msg ",
     Toast.LENGTH_LONG).show();
  } else if (item.getTitle() == "Call") {
   Toast.makeText(getApplicationContext(), "U selected Call ",
     Toast.LENGTH_LONG).show();
  } else if (item.getTitle() == "Email") {
   Toast.makeText(getApplicationContext(), "U selected Email ",
     Toast.LENGTH_LONG).show();
  } else if (item.getTitle() == "Note") {
   Toast.makeText(getApplicationContext(), "U selected Note ",
     Toast.LENGTH_LONG).show();
  } else if (item.getTitle() == "Meeting") {
   Toast.makeText(getApplicationContext(), "U selected Meeting ",
     Toast.LENGTH_LONG).show();
  }

  return false;
 }



 //Option Menu----------------------------------------
  //here I am creating options menu from menu.xml file. 
       @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  MenuInflater m = getMenuInflater();
  m.inflate(R.menu.main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // Handle action bar item clicks here. The action bar will
  // automatically handle clicks on the Home/Up button, so long
  // as you specify a parent activity in AndroidManifest.xml.
  switch (item.getItemId()) {
  case R.id.home:
   Toast.makeText(getApplicationContext(), "U selected Home Option ",
     Toast.LENGTH_LONG).show();
   break;
  case R.id.add:
   Toast.makeText(getApplicationContext(), "U selected Add Option ",
     Toast.LENGTH_LONG).show();
   break;
  case R.id.delete:
   Toast.makeText(getApplicationContext(), "U selected Delete Option ",
     Toast.LENGTH_LONG).show();
   break;
  case R.id.logout:
   Toast.makeText(getApplicationContext(), "U selected Logout Option ",
     Toast.LENGTH_LONG).show();
   break;

  default:
   break;
  }
  return super.onOptionsItemSelected(item);
 }

 @Override
 public void onBackPressed() {
     moveTaskToBack(true);
 }

 // Before 2.0
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK) {
         moveTaskToBack(true);
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }

}

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.allmenudemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="20" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/studentprofile"
        android:label="@string/app_name"
        android:theme="@style/Theme.Example" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         </application>

</manifest>
Now, Run The Application. Stay tune for next Session Happy codding :)