简体   繁体   中英

PopupMenu - how to?

I am beginner in android and try to make an app that popup a menu when imageView is clicked. Actually it works but popup at right side and I want to be at center. So, I searched for it on web and come across ListPopupWindow, PopupWindow classes. I tried various methods of this classes as per my knowledge/ability but I am not able to achieve this. Guide me to do that. Here is my code

imageview setonclickListener(new View.onclickListener() {
    @Override public void onClick(View view){
        PopupMenu popup = new PopupMenu(Info4 Activity.this, imageview1);
        Menu menu = popup.getMenu();
        for (int i = 0; i < (int) (subjects.size()); i++) {
            val = subjects.get((int) (i));
            menu.add(val);
        }
        popup.show();
    }
});

弹出菜单

PopupMenu :

The popup will appear below the anchor if there is room, or above it if there is not. In your situation the anchor is imageView , so you can not center the popup in screen.

PopupWindow :

Try this:

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
               popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);// here v is any View only needed for WindowToken
        }
    });

Other better ways:

May be you could be think about using DialogFragment , which is customizable and flexible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM