create a popup menu - Android User Interface

Android examples for User Interface:PopupMenu

Description

create a popup menu

Demo Code


import android.app.Dialog;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

public class Main{
    public static final int WIDTH = 0;
    public static final int HEIGHT = 1;
    /*from  ww  w.ja  v a  2  s .  c o  m*/
    public static Dialog makePopup(Context context, View contentView) {
        Dialog dialog = new Dialog(context, R.style.popupDialog);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();
        int[] size = getScreenSize(context);
        windowParams.x = 0;
        windowParams.y = size[HEIGHT];

        //window?
        window.setAttributes(windowParams);
        // window.setBackgroundDrawableResource(R.drawable.alert_dialog_background);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(contentView);
        // ?contentView 
        dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        return dialog;
    }
    /**
     * get device size
     * @param context
     * @return 
     */
    public static int[] getScreenSize(Context context) {
        int[] deviceSize = new int[2];
        int w = 0;
        int h = 0;
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        w = dm.widthPixels;
        h = dm.heightPixels;
        deviceSize[WIDTH] = w;
        deviceSize[HEIGHT] = h;
        return deviceSize;
    }
}

Related Tutorials