Skip to content Skip to sidebar Skip to footer

Imagebutton Does Not Display Menu Items When Pressing It

I have a custom ListView. Inside the layout of the custom ListView, I have an ImageButton which acts as an overflow menu (similar to how the Menu on the ActionBar works): layout/it

Solution 1:

This Questions is duplication. For custom layouts you can't use a menu, you have to use to a PopupWindow

Android MenuItem Custom Layout

PopupWindowpopupwindow_obj= popupDisplay();
popupwindow_obj.showAsDropDown(clickbtn, -40, 18); // where u want show on view click event popupwindow.showAsDropDown(view, x, y);public PopupWindow popupDisplay() 
{ 

    finalPopupWindowpopupWindow=newPopupWindow(this);

    // inflate your layout or dynamically add viewLayoutInflaterinflater= (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    Viewview= inflater.inflate(R.layout.mylayout, null);

    Buttonitem= (Button) view.findViewById(R.id.button1);

    popupWindow.setFocusable(true);
    popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
    popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
    popupWindow.setContentView(view);

    return popupWindow;
}

// Create this XML file in the res/layout folder named my layout.xml

<LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Window test" /></LinearLayout>

Solution 2:

Firstly PopupMenu is exactly what you need . From the docs

A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. It's good for providing an overflow of actions that relate to specific content or to provide options for a second part of a command.

Now the reason why your implementation doesn't work is because onCreateOptionsMenu and onMenuItemClick are for managing the menu for the activity so inflating the overflow menu there is pointless.

What you need to do is attach an onClickListener to your ImageButton and initialize the PopupMenu and call show()inside your ListView/RecyclerView adapter

imageButton = findViewById(R.id.overflow_menu);
PopupMenupopup=newPopupMenu(this, imageButton);
MenuInflaterinflater= popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
imageButton.setOnClickListener(newView.OnClickListener(){
    @OverridepublicvoidonClick(View v) {
        popup.show();
    }    
});

You can have a look at the docs linked above for examples as well.

Post a Comment for "Imagebutton Does Not Display Menu Items When Pressing It"