Android - Popup menu when list item view pressed?
Asked Answered
A

7

14

i would like to implement a popup menu similar to google's play store as shown below.

enter image description here

so basically from what i understand, i'll need an activity and a layout for this activity with a listview defined in it. i need to create my custom adapter. also, i need to create a list layout would contain the information and a view (with the 3 dots) that will serve as the button to launch the popup menu? the issue that i'm seeing here is that how do i create a listener for this view only and how do i reference the value for that specific list item in the list view.

i don't have any code available yet as i haven't started anything related to this. i'm currently getting info in theory for now but if required i will create a sample code.

thanks.

Aristocratic answered 3/9, 2013 at 9:32 Comment(2)
you can open pop up menu onItemClick method of listview.Renwick
fist start then come back after u have tried something..And go through listView tutorial.Be practicalSignesignet
W
22

Using popup menu it's quite simple to create a menu with these three steps:

1 - Add a click listener to the menu button using OnClickListener or as i prefer from the layout xml:

<ImageButton android:id="@+id/menu_button" android:onClick="showMenu" ... />

2 - Create the menu layout menu_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/item_settings"
        android:showAsAction="ifRoom|withText"
        android:title="Settings"
        android:visible="true"/>
    <item
        android:id="@+id/item_about"
        android:showAsAction="ifRoom|withText"
        android:title="About"
        android:visible="true"/>
</menu>

3 - Create a popup menu, inflate the xml layout and show it:

public void showMenu (View view)
{
    PopupMenu menu = new PopupMenu (this, view);
    menu.setOnMenuItemClickListener (new PopupMenu.OnMenuItemClickListener ()
    {
        @Override
        public boolean onMenuItemClick (MenuItem item)
        {
            int id = item.getItemId();
            switch (id)
            {
                case R.id.item_settings: Log.i (Tag, "settings"); break;
                case R.id.item_about: Log.i (Tag, "about"); break;
            }
            return true;
        }
    });
    menu.inflate (R.menu.menu_layout);
    menu.show();
}
Writhe answered 3/1, 2016 at 2:1 Comment(2)
elegant answer, simplest one i hv found ! Saved my dayErlandson
How to show icons with the options menu? The android:icon is not working for me.Mielke
A
8

You can use like this:

public class MainActivity extends Activity {
    ListView listView_Actions;
    ArrayList<String> actionsArrayList;
    Button btn_ViewPopUp;
    ArrayAdapter<String> actionsAdapter;
    static final int CUSTOM_DIALOG_ID1 = 1;

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

        actionsArrayList=new ArrayList<String>();
        actionsArrayList.add("Action 1");
        actionsArrayList.add("Action 2");
    }

    @Override
    protected void onStart() {
        super.onStart();

        btn_ViewPopUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(CUSTOM_DIALOG_ID1);
                actionsAdapter = new MyCustomBaseAdapter(getApplicationContext(), R.layout.list_actions, actionsArrayList);
                listView_Actions.setAdapter(actionsAdapter);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch (id) {
            case CUSTOM_DIALOG_ID1:
                dialog = new Dialog(MainActivity.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.setContentView(R.layout.list_actions);
                listView_Actions = (ListView) dialog.findViewById(R.id.listView_Actions);
                break;
        }
        return dialog;
    }

    class MyCustomBaseAdapter extends ArrayAdapter<String> 
    {
        public MyCustomBaseAdapter(Context context, int textViewResourceId, ArrayList<String> actionsArrayList) {
            super(context, textViewResourceId,actionsArrayList);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.action_list_cell, null);
            final TextView lblContactAction;
            lblContactAction = (TextView) v.findViewById(R.id.txtContactAction);

            lblContactAction.append(actionsArrayList.get(position));
            return v;
        }
    }
}

Now XML files:

action_list_cell.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/background_light" >

    <TextView
        android:id="@+id/txtContactAction"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
         android:textSize="18dp"
        android:textColor="@android:color/black" />

</LinearLayout>

list_actions.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="@drawable/rounded_corner_top">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#DB6A16"
            android:orientation="vertical"
            android:paddingBottom="2dp"
            android:paddingLeft="2dp"
            android:paddingRight="2dp" >

            <ListView
                android:id="@+id/listView_Actions"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#ffffff" >
            </ListView>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
Asynchronism answered 3/9, 2013 at 10:6 Comment(3)
nice...! I use same method. :)Grin
Hi i have used your code inside Fragments but protected Dialog onCreateDialog(int id) Method is not present in Fragments , what should i do ?Vesicle
Now showDialog is deprecated. use PopupMenu insteadLearn
A
8

ActionBarCompat List PopupMenu implementation is here (with back port available because it uses ABC)!

enter image description here

You can also get this sample from Github or from SDK (Mr.Morgan commented below)

/sdk/samples/android-19/ui/ActionBarCompat-ListPopupMenu. Make sure to install Samples for SDK under Android 4.4.2 (API 19)

Alika answered 7/2, 2014 at 11:49 Comment(2)
Where to get this example ?Legrand
@zest This example can be found in /sdk/samples/android-19/ui/ActionBarCompat-ListPopupMenu. Make sure to install Samples for SDK under Android 4.4.2 (API 19).Unconventional
D
4

first of all you need to make your custom adapter with a view that has the 3 dots.

then in the getView() or newView() method you set the listener to the 3 dots image.

i think that PopupMenu is what you are looking for, it's is supported since API 11.

if you want to support also earlier version of the API you can use PopupMenu class provided by the support library v7.

the usage is pretty straight forward. you define it with the id of the view you want the menu to show next to, and then you can directly inflate a menu resource there as if it was a common menu.

Dominquedominquez answered 3/9, 2013 at 9:44 Comment(0)
L
2

Now showDialog is deprecated, use PopupMenu instead And AppCompat PopupMenu f you want to support version before V11

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  
         }  
    }  
Learn answered 9/2, 2015 at 13:42 Comment(0)
P
0

You have to set the Listener of the Button in the getView()-Method of your List-Adapter. In this getView()-Method you assign a Layout to one List-Item. if you have done this, you just have to set the Listener on this View (Button), and handle the onClick() Event.

Pycno answered 3/9, 2013 at 9:42 Comment(0)
P
0

Not sure if i understand you correctly but you can trigger this method to open a pop up dialog with a listview.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Title if Any");
    builder.setItems(R.array.listoptions, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int itemClicked) {
                   String[] option_array = getResources().getStringArray(R.array.listoptions);

                   String optionSelected = option_array[itemClicked];
           }
    });
    return builder.create();
}

See Adding a List

 <?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listoption">
    <item>Install</item>
    <item>Add to listview</item>
</string-array>
</resources>

Hope this helps.

Partly answered 3/9, 2013 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.