20 Mar 2014

Popup Menu | List Popup Menu Android Example

Hello Friends,

Popup menu is a modal menu that is anchored on a view. It is either displayed below if there is enough room or above the view. Popup menu is introduced in Android HoneyComb ( API level 11 ) version.
Here is the sample which is work for all android version it is display any position on screen
In this application, a popup menu will be displayed on clicking a button available in the Main Activity.

Output Screen:



SampleActivity.java 


import hb.popupmenu.lib.MenuItem;
import hb.popupmenu.lib.PopupMenu;
import hb.popupmenu.lib.PopupMenu.OnItemSelectedListener;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SampleActivity extends ListActivity implements OnItemSelectedListener 
{
 private final static int PLAY_SELECTION = 0;
 private final static int ADD_TO_PLAYLIST = 1;
 private final static int SEARCH = 2;

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);

  String[] array = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
  setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array));
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) 
 {
  // Create Instance
  PopupMenu menu = new PopupMenu(this);
  menu.setHeaderTitle("Popup Menu");
  // Set Listener
  menu.setOnItemSelectedListener(this);
  // Add Menu (Android menu like style)
  menu.add(PLAY_SELECTION, R.string.play).setIcon(
    getResources().getDrawable(R.drawable.ic_context_menu_play_normal));
  menu.add(ADD_TO_PLAYLIST, R.string.add_to_playlist).setIcon(
    getResources().getDrawable(R.drawable.ic_context_menu_add_to_playlist_normal));
  menu.add(SEARCH, R.string.search).setIcon(
    getResources().getDrawable(R.drawable.ic_context_menu_search_normal));
  menu.show(v);
 }

 @Override
 public void onItemSelected(MenuItem item) 
 {
  switch (item.getItemId()) 
  {
  case PLAY_SELECTION:
   break;

  case ADD_TO_PLAYLIST:
   break;

  case SEARCH:
   break;

  }
 }
}


Download Full source code from here Popup menu

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

2 comments:

  1. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai

    ReplyDelete
  2. Very informative ..i suggest this blog to my friends..Thank you for sharing
    Android Training in chennai

    ReplyDelete