Popupwindow的简介与简单使用

本文详细介绍了如何在Android中使用PopupWindow,包括相对于兄弟控件和父类控件弹出弹框的方法,以及如何设置大小、位置和交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Poupwindow

PopupWindow相对于兄弟控件的弹框

在这里插入图片描述

// 相对于兄弟控件
rivate void getPopupWindow() {

        PopupWindow popupWindow = new PopupWindow(this);
        //把Xml文件转化为View对象
        View view = View.inflate(this, R.layout.sim, null);
        //找到相对应的控件 可以给控件添加额外操作
        button = view.findViewById(R.id.button1);
        //给控件设置大小
        popupWindow.setHeight(200);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

//给popupwindow关联布局
        popupWindow.setContentView(view);

        popupWindow.setOutsideTouchable(true);

//0为X轴的偏移量 200位Y轴偏移量 兄弟布局用showASdropdown
        popupWindow.showAsDropDown(tv,0,200);

    }

PopupWindow相对于父类控件的弹框

在这里插入图片描述

//相对于父控件
private void getPopupWindow1() {

        final PopupWindow popupWindow = new PopupWindow(this);
        //把Xml文件转化为View对象
        View view = View.inflate(this, R.layout.sim, null);
        button = view.findViewById(R.id.button1);
        popupWindow.setHeight(200);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);


//给子控件添加吐司
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "你点了我", Toast.LENGTH_SHORT).show();
            }
        });
        popupWindow.setContentView(view);

        popupWindow.setOutsideTouchable(true);

//找到父容器布局
        View view1 = View.inflate(this, R.layout.activity_main, null);


        WindowManager.LayoutParams attributes = getWindow().getAttributes();

//给布局添加透明度 0.5f单位为float 1.0f为完全透明
        attributes.alpha = 0.5f;
        getWindow().setAttributes(attributes);
        //设置点击popupwindow外面设置透明度还原 
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                WindowManager.LayoutParams attributes = getWindow().getAttributes();

                attributes.alpha = 1.0f;
                getWindow().setAttributes(attributes);
            }
        });

//相对于父控件 showAtLocation
        popupWindow.showAtLocation(view1, Gravity.BOTTOM, 0, 0);


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值