Android的自定义Menu使用PopupWindow实现


    Android的对话框有两种:PopupWindow和AlertDialog。

    它们的不同点在于:

    1)AlertDialog的位置固定,而PopupWindow的位置可以随意
    2)AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的
    3)PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,可以分为相对于某个控件和相对于父控件。具体如下:
showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移

showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移。

    先上几张效果图吧:


    首先,在layout下增加两个布局文件,第一个为menu.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    android:id="@+id/menu"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1b2936"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <GridView
        android:gravity="center"
        android:id="@+id/menuGridChange"
        android:background="#1b2936"
        android:layout_alignParentBottom="true"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="400dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="10.0dip"
        android:verticalSpacing="60.0dip"
        android:columnWidth="60.0dip"
        android:numColumns="3"
        />
</LinearLayout>

    然后是main.xml:

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:layout_gravity="center"
        android:text="Menu按钮"
        />


</LinearLayout>

    最后是MenuText.java的完整代码:

public class MenuTest extends Activity implements OnItemClickListener {
    private PopupWindow pw;
    private LayoutInflater inflater ;
    private Button btn;
    private LinearLayout linearLayout;


    private int[] resArray = new int[]{
            R.drawable.more_membership,
            R.drawable.more_trip, R.drawable.more_share
            , R.drawable.more_return
    };
    private String[] title = new String[]{
            "会员信息", "寻找之旅", "分享"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.btn);
        View view = LayoutInflater.from(this).inflate(R.layout.menu, null);
        linearLayout = (LinearLayout) view.findViewById(R.id.menu);
        linearLayout.getBackground().setAlpha(200);//设置透明度,0为完全透明,255为完全不透明


        inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.menu, null);
        GridView grid1 = (GridView) view.findViewById(R.id.menuGridChange);
        grid1.setOnItemClickListener(this);
        grid1.setFocusableInTouchMode(true);
        grid1.setAdapter(new ImageAdapter(this));
         /*第一个参数弹出显示view  后两个是窗口大小*/
        pw = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        /*设置点击menu以外其他地方以及返回键退出*/
        pw.setFocusable(true);
         /*设置背景显示*/
        pw.setBackgroundDrawable(new ColorDrawable());
        /*设置再次按菜单键时退出*/
        grid1.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_MENU) && (pw.isShowing())) {
                    pw.dismiss();
                    return true;
                }
                return false;
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pw.showAtLocation(findViewById(R.id.btn), Gravity.CENTER, 0, 100);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");// 必须创建一项
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 拦截MENU
     */
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (pw != null) {
            if (!pw.isShowing()) {
                /*最重要的一步:弹出显示   在指定的位置(parent)  最后两个参数 是相对于 x / y 轴的坐标*/
                pw.showAtLocation(findViewById(R.id.btn), Gravity.CENTER, 0, 100);
            } else {
                pw.dismiss();
            }
        }
        return false;// 返回为true 则显示系统menu
    }

    public class ImageAdapter extends BaseAdapter {

        private Context context;

        public ImageAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return resArray.length + 1;
        }

        @Override
        public Object getItem(int position) {
            return resArray[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup arg2) {
            if (position < 3) {
                LinearLayout linear = new LinearLayout(context);
                linear.setOrientation(LinearLayout.VERTICAL);
                //装进一张图片
                ImageView iv = new ImageView(context);
                iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[position])).getBitmap());
                LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.gravity = Gravity.CENTER;
                linear.addView(iv, lp);
                //显示文字
                TextView tv = new TextView(context);
                tv.setText(title[position]);
                linear.addView(tv, lp);

                return linear;
            } else if (position == 4) {
                ImageView iv = new ImageView(context);
                iv.setImageBitmap(((BitmapDrawable) context.getResources().
                        getDrawable(resArray[3])).getBitmap());
                return iv;
            } else {
                TextView textView = new TextView(context);
                return textView;
            }

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        switch (position) {
            case 0:
                Toast.makeText(this, "会员信息", Toast.LENGTH_LONG).show();
                break;
            case 1:
                Toast.makeText(this, "寻找之旅", Toast.LENGTH_LONG).show();
                break;
            case 2:
                Toast.makeText(this, "分享", Toast.LENGTH_LONG).show();
                break;
            case 4:
                pw.dismiss();

                break;
        }
    }

}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值