引言
??之前我做了自定義Dialog彈出框阁将,但我發(fā)現(xiàn)在實(shí)際的使用中其顏色會(huì)與背景白色顯示相沖突,不會(huì)凸顯出自定義Dialog彈出框的白色背景效果磁椒。而非自定義的Dialog它本身自帶彈出時(shí)背景顏色變暗+消失時(shí)背景顏色恢復(fù)的效果空镜,我就在想如何自定義實(shí)現(xiàn)這個(gè)效果呢?
??于是痘绎,通過(guò)動(dòng)畫(huà),實(shí)現(xiàn)了漸變色效果肖粮,當(dāng)彈出Dialog時(shí)孤页,除彈出提示框外的主布局背景逐漸暗化;當(dāng)Dialog消失時(shí)涩馆,主布局背景逐漸恢復(fù)原色行施。主要通過(guò)控制主布局背景的透明度來(lái)實(shí)現(xiàn)。
實(shí)現(xiàn)效果
傳送門(mén)
[兄弟篇]自定義Dialog實(shí)現(xiàn)“退出應(yīng)用程序”效果
新增自定義方法:兩個(gè)
/**
* 設(shè)置透明度
*/
private void setBackgroundAlpha(float bgAlpha) {
WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
lp.alpha = bgAlpha;
((Activity) mContext).getWindow().setAttributes(lp);
}
/**
* 顯示彈窗魂那,過(guò)程中伴隨背景逐漸變暗蛾号。
* 不要改變MaskLayout的背景色,否則會(huì)是灰色背景的框框整體向上升起的效果涯雅。
*/
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類(lèi)中(以下三步都是)
(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時(shí)背景變暗鲜结,消失時(shí)恢復(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類(lèi)中重寫(xiě)的onCreate方法中調(diào)用show(View parent)方法進(jìn)行顯示。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mydialog_layout);
......
......
show(contentView);
}