本文的合集已经编著成书,高级Android开发强化实战,欢迎各位读友的建议和指导。在京东即可购买:https://item.jd.com/12385680.html
Android对于底部弹窗已经在23.2新的实现方式, 即BottomSheet. 然而对于低版本, 我们仍需使用DialogFragment. 底部弹窗与普通Dialog不同, 需要紧贴应用下部, 但本质仍是一个Fragment, 通过继承DialogFragment类, 定制不同样式的Fragment.
本文源码的GitHub下载地址
定制DialogFragment
底部弹窗, 需要紧贴应用下部. 设置Dialog样式(Style), 全屏/布局/外部取消. 设置Dialog位置(LayoutParams), 底部/宽度最大.
@NonNull @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
Dialog dialog = new Dialog(getActivity(), R.style.BottomDialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
dialog.setContentView(R.layout.fragment_bottom);
dialog.setCanceledOnTouchOutside(true); // 外部点击取消
// 设置宽度为屏宽, 靠近屏幕底部。
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.gravity = Gravity.BOTTOM; // 紧贴底部
lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
window.setAttributes(lp);
ButterKnife.bind(