自定义半透明PopupWindow

实现效果

Paste_Image.png
Paste_Image.png

贴上代码

public class MainActivity extends AppCompatActivity {

private PopupWindow popupWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tvEnlist = (TextView) findViewById(R.id.tvEnlist);
    final LinearLayout bottomBar = (LinearLayout) findViewById(R.id.bottomBar);
    tvEnlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showPopupWindow(bottomBar);
        }
    });
}

public void showPopupWindow(View parent) {
    WindowManager.LayoutParams lp = getWindow()
            .getAttributes();
    lp.alpha = 0.4f;
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    getWindow().setAttributes(lp);
    //加载布局
    View layout = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(pop, null);
    TextView tvEnlist = (TextView) layout.findViewById(R.id.tvEnlist);
    TextView tvCancel = (TextView) layout.findViewById(R.id.tvCancel);
    tvEnlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
        }
    });
    tvCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
        }
    });
    // 实例化popupWindow
    popupWindow = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    //控制键盘是否可以获得焦点
    popupWindow.setFocusable(true);
    popupWindow.setTouchable(true);
    popupWindow.setOutsideTouchable(true);
    //设置popupWindow弹出窗体的背景
    popupWindow.setBackgroundDrawable(new BitmapDrawable(null, ""));
    WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    @SuppressWarnings("deprecation")
    int[] location = new int[2];
    parent.getLocationOnScreen(location);
    popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, location[0], location[1] - popupWindow.getHeight());
    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            recoveryAlpha();
        }
    });
}

private void recoveryAlpha() {
    WindowManager.LayoutParams lp = MainActivity.this.getWindow()
            .getAttributes();
    lp.alpha = 1f;
    MainActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    MainActivity.this.getWindow().setAttributes(lp);
}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容