根据需求,如果经常复用的话,建议单独写一个继承Dialog的底部弹窗类,如果只用一遍的话,可以选择直接new Dialog来快速创建一个窗口。
先准备好窗口的style和动画的style:
<style name="BottomDialog" parent="@style/Base.V7.Theme.AppCompat.Light.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
<style name="BottomDialog.Animation" parent="Animation.AppCompat.Dialog">
<item name="android:windowEnterAnimation">@anim/translate_dialog_in</item>
<item name="android:windowExitAnimation">@anim/translate_dialog_out</item>
</style>
动画xml:
tranlate_dialog_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="0"
android:fromYDelta="100%"
android:toXDelta="0"
android:toYDelta="0">
</translate>
tranlate_dialog_out.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="0"
android:fromYDelta="0"
android:toXDelta="0"
android:toYDelta="100%">
</translate>
上面说的两种方式:
1、new Dialog方式:
View view = LayoutInflater.from(this).inflate(R.layout.dialog_wentai_first_launch, null);
bottomDialog = new Dialog(context);
bottomDialog.setTitle(title);
Window window = bottomDialog.getWindow();
window.setGravity(Gravity.BOTTOM);
window.setContentView(view);
WindowManager.LayoutParams lp = window.getAttributes();
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);
//设置弹出与收起的动画,如果不需要动画可以去掉这句
bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
bottomDialog.show();
2、类继承方式:(拓展通用性,在构造函数传入viewId进来):
public class BottomDialog extends Dialog {
private View layoutView;
public BottomDialog(Context context,int layoutId) {
super(context, R.style.BottomDialog);
layoutView = LayoutInflater.from(context).inflate(layoutId,null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layoutView);
Window window = this.getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setGravity(Gravity.BOTTOM);
window.setAttributes(params);
window.setWindowAnimations(R.style.BottomDialog_Animation);
}
public BottomDialog setOnClickListener(@IdRes int viewId, View.OnClickListener listener){
layoutView.findViewById(viewId).setOnClickListener(listener);
return this;
}
public <T extends View> T getView(@IdRes int viewId){
return layoutView.findViewById(viewId);
}
}
//调用
BottomDialog dialog = new BottomDialog(this,R.layout.dialog_bottom);
//TextView tv = dialog.getView(R.id.xxxx);
dialog.show();
//关闭
dialog.dismiss();