一个类似淘宝弹出框的示例

效果如图


一个类似淘宝弹出框的示例_第1张图片



代码如下:

Button show;
RelativeLayout main;
private PopupWindow mPopupWindow;
private View mView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    show = (Button) findViewById(R.id.show);
    main = (RelativeLayout) findViewById(R.id.main);

    //这个是你弹出框需要的布局
    mView = View.inflate(MainActivity.this, R.layout.example_pop, null);
   
    Button button = (Button) mView.findViewById(R.id.button_show);
    
    //这个是实验弹出框的点击事件是否可以响应
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "出现吧", Toast.LENGTH_SHORT).show();

        }
    });
    
    mPopupWindow = new PopupWindow(mView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    mPopupWindow.setFocusable(true);
    mPopupWindow.setOutsideTouchable(true);
    mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
    mPopupWindow.getContentView().setFocusableInTouchMode(true);
    mPopupWindow.getContentView().setFocusable(true);




    mPopupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (mPopupWindow != null && mPopupWindow.isShowing()) {

                    mPopupWindow.dismiss();

                }
                return true;
            }
            return false;
        }
    });
    mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            AlphaAnimation alphaAnimation = new AlphaAnimation(0.5f, 1.0f);

            alphaAnimation.setFillAfter(true);
            main.startAnimation(alphaAnimation);
        }
    });

    show.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.5f);

            alphaAnimation.setFillAfter(true);
            main.startAnimation(alphaAnimation);
            mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        }
    });
}

你可能感兴趣的:(一个类似淘宝弹出框的示例)