我们使用Dialog来实现中间弹框和底部弹框两种效果
第一种:底部弹框
效果如下图:
1、定义DemoDialog,继承Dialog
public class DemoDialog extends Dialog {
DemoDialogClickCallback demoDialogClickCallback;
Context context;
String title;
String content;
public DemoDialog(@NonNull Context context, String title, String content,DemoDialogClickCallback demoDialogClickCallback) {
super(context);
this.context = context;
this.content = content;
this.title = title;
this.demoDialogClickCallback=demoDialogClickCallback;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_demo);
Window window = getWindow();
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//底部弹框效果
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.BOTTOM);
window.setWindowAnimations(R.style.animate_dialog);
//中间弹框效果
// window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// window.setGravity(Gravity.CENTER);
TextView titleView=findViewById(R.id.title);
TextView contentView=findViewById(R.id.content);
Button buttonView=findViewById(R.id.i_know);
buttonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
demoDialogClickCallback.iKonw();
}
});
titleView.setText(this.title);
contentView.setText(this.content);
setCanceledOnTouchOutside(false);
}
public interface DemoDialogClickCallback {
public void iKonw();
}
}
2、设置弹框的入场出场动画 animate_dialog
<style name="animate_dialog">
<item name="android:windowEnterAnimation">@anim/anim_bottom_in</item>
<item name="android:windowExitAnimation">@anim/anim_bottom_out</item>
</style>
3、调用方法
demoDialog = new DemoDialog(this, "小区公告", "今天晚上在惠民广场,红星乐队惊艳演出,同志们都来参见!!", new DemoDialog.DemoDialogClickCallback() {
@Override
public void iKonw() {
demoDialog.dismiss();
}
});
demoDialog.show();
第二种:中间弹框
效果如下:
弹框位置控制的关键属性
把
window.setGravity(Gravity.BOTTOM);
改成
window.setGravity(Gravity.CENTER);
即可实现