Popupwindow的简介与简单使用
程序员文章站
2022-05-31 10:54:50
...
Popupwindow
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);
}