1.创建弹出窗口布局文件,例如popup_window.xml:
2.在Activity中调用弹出窗口,例如MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnPopup = findViewById(R.id.btn_popup);
btnPopup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 创建弹出窗口对象
PopupWindow popupWindow = new PopupWindow(MainActivity.this);
// 设置弹出窗口的属性
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_window, null);
popupWindow.setContentView(view);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
// 设置弹出窗口中的事件
Button btnClose = view.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
// 显示弹出窗口
popupWindow.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
}
});
}
}
在此代码中,我们在MainActivity中创建了一个按钮btnPopup,并在其中创建了一个单击事件。单击事件中,我们先创建PopupWindow对象。然后