
退出app.jpeg
引言
??之前我做了自定義Dialog彈出框,但我發(fā)現(xiàn)在實際的使用中其顏色會與背景白色顯示相沖突,不會凸顯出自定義Dialog彈出框的白色背景效果。而非自定義的Dialog它本身自帶彈出時背景顏色變暗+消失時背景顏色恢復(fù)的效果,我就在想如何自定義實現(xiàn)這個效果呢?
??于是,通過動畫,實現(xiàn)了漸變色效果,當彈出Dialog時,除彈出提示框外的主布局背景逐漸暗化;當Dialog消失時,主布局背景逐漸恢復(fù)原色。主要通過控制主布局背景的透明度來實現(xiàn)。
實現(xiàn)效果

退出app背景變暗.gif
傳送門
[兄弟篇]自定義Dialog實現(xiàn)“退出應(yīng)用程序”效果
新增自定義方法:兩個
/**
* 設(shè)置透明度
*/
private void setBackgroundAlpha(float bgAlpha) {
WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
lp.alpha = bgAlpha;
((Activity) mContext).getWindow().setAttributes(lp);
}
/**
* 顯示彈窗,過程中伴隨背景逐漸變暗。
* 不要改變MaskLayout的背景色,否則會是灰色背景的框框整體向上升起的效果。
*/
public void show(View parent) {
ValueAnimator animator = ValueAnimator.ofFloat(1, 0.5f).setDuration(500);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setBackgroundAlpha((Float) animation.getAnimatedValue());
}
});
animator.start();
}
具體如何調(diào)用
自定義SelfDialog類中(以下三步都是)
(1)首先聲明
//上下文環(huán)境
Context mContext;
View contentView;
(2)在構(gòu)造函數(shù)中的邏輯代碼
public SelfDialog(@NonNull Context context) {
super(context, R.style.MyDialog); //構(gòu)造方法中設(shè)置Dialog的樣式
this.mContext = context;
contentView = LayoutInflater.from(mContext).inflate(R.layout.popup_select_layout, null);
/**
* 顯示Dialog時背景變暗,消失時恢復(fù)亮度
*/
setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
ValueAnimator animator = ValueAnimator.ofFloat(0.5f, 1f).setDuration(500);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setBackgroundAlpha((Float) animation.getAnimatedValue());
}
});
animator.start();
}
});
}
(3)同樣在SelfDialog類中重寫的onCreate方法中調(diào)用show(View parent)方法進行顯示。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mydialog_layout);
......
......
show(contentView);
}