Search code examples
javaandroidandroid-imageview

how can i display items when we click imageView


I'm struggling to use ImageView as a button that I need when I click it should display items, like when we click a spinner the same procedure.

final View imageButton = findViewById(R.id.imageButton);
 imageButton.setOnClickListener(new OnClickListener(){
 @Override
 public void onClick(View view) {
            // display a list of suggestions !
        }
    });

I will be thankful if there is anyone who gonna help me to solve this problem.


Solution

  • First you create your menu of items you want to show like this

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item
    android:id="@+id/first"
    android:title="First Menu Item"/>
    
    <item
    android:id="@+id/second"
    android:title="Second Menu Item"/>
    
    <item
    android:id="@+id/third"
    android:title="Third Menu Item"/>
    
    </menu>
    

    Then in your Activity you create a PopupMenu

    PopupMenu pm = new PopupMenu(MainActivity.this, pBtn);
        pm.getMenuInflater().inflate(R.menu.popup_menu, pm.getMenu());
        pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.first:
                        Toast.makeText(MainActivity.this, "Clicked First Menu Item", Toast.LENGTH_SHORT).show();
                        return true;
    
                    case R.id.second:
                        Toast.makeText(MainActivity.this, "Clicked Second Menu Item", Toast.LENGTH_SHORT).show();
                        return true;
    
                    case R.id.third:
                        Toast.makeText(MainActivity.this, "Clicked Third Menu Item", Toast.LENGTH_SHORT).show();
                        return true;
                }
    
                return true;
            }
        });
        pm.show();
    

    Finally you call this popup menu in your click listener

    EDIT:

    Create an ArrayList of String for example

    ArrayList<String> popupItems = new ArrayList<String>();
    

    Fill your arraylist with your data

    Then you initialize your popupmenu with this array list

    popupMenu = new PopupMenu(this, imageButton); 
    

    Loop through your array add values to the popupmenu menu

    for (int i =0; i < popupItems.size(); i++)
        popupMenu.getMenu().add(Menu.NONE, 1, Menu.NONE, popupItems.get(i))