使用PopupWindow很简单,可以总结为三个步骤:
- 创建PopupWindow对象实例;
- 设置背景、注册事件监听器和添加动画;
- 显示PopupWindow。
先来看下效果图:
下面来看下代码的的实现
PopupWindow的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<com.sinosig.ygqd.widget.CustomHeightImageView
android:id="@+id/iv_popup_hand_idCard"
android:layout_width="846.7px"
android:layout_height="wrap_content"
app:scale="0.6361"
android:src="@mipmap/icon_poput_card"
/>
</LinearLayout>
代码中显示PopupWindow:
// 用于PopupWindow的View
View view= LayoutInflater.from(this).inflate(R.layout.popup_hand_idcard,null,false);
// 创建PopupWindow对象,第一个参数PopupWindow的宽,第二个参数PopupWindow的高
PopupWindow popup1=new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
//设置PopupWindow的view
popup1.setContentView(view);
// 设置PopupWindow的背景
popup1.setBackgroundDrawable(new BitmapDrawable());
// 设置PopupWindow是否能响应外部点击事件
popup1.setOutsideTouchable(true);
//PopupWindow 消失的监听
popup1.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//Activity设置为不透明
setWindowAlpa(false);
}
});
}
popup1.showAtLocation(iv_hand_idCard, Gravity.CENTER,0,0);
//PopupWindow 设置成半透明
setWindowAlpa(true);
动态设置Activity半透明的方法:
/**
* 动态设置Activity背景透明度
*
* @param isopen
*/
public void setWindowAlpa(boolean isopen) {
if (Build.VERSION.SDK_INT < 11) {
return;
}
final Window window = this.getWindow();
final WindowManager.LayoutParams lp = window.getAttributes();
window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND);
ValueAnimator animator;
if (isopen) {
animator = ValueAnimator.ofFloat(1.0f, 0.5f);
} else {
animator = ValueAnimator.ofFloat(0.5f, 1.0f);
}
animator.setDuration(400);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float alpha = (float) animation.getAnimatedValue();
lp.alpha = alpha;
window.setAttributes(lp);
}
});
animator.start();
}