- 自定义PopupWindow的布局文件 dialog_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:src="@mipmap/ic_launcher"
android:layout_marginTop="50dp"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A Dialog"
/>
</LinearLayout>
2.定义显示和隐藏的动画,并设置style
(1) 进场时的动画 popup_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
>
<!-- 平移动画 -->
<translate
android:fromYDelta="-100%p"
android:toYDelta="0"
android:duration="1000"
/>
</set>
(2) 退场时的动画 popup_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
>
<!-- 平移动画 -->
<translate
android:fromYDelta="0"
android:toYDelta="-100%p"
android:duration="1000"
/>
</set>
(3) 设置样式
<style name="PopupAnimation" parent="android:Animation" mce_bogus="1">
<item name="android:windowEnterAnimation">@anim/popup_in</item>
<item name="android:windowExitAnimation">@anim/popup_out</item>
</style>
3.实现
private void showPopupWindow() {
// 一个自定义的布局,作为显示的内容
View contentView = LayoutInflater.from(TestActivity.this).inflate(
R.layout.dialog_layout, null);
final PopupWindow popupWindow = new PopupWindow(contentView,
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
popupWindow.setTouchable(true);
popupWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("mengdd", "onTouch : ");
return false;
// 这里如果返回true的话,touch事件将被拦截
// 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
}
});
// 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
// 我觉得这里是API的一个bug
//popupWindow.setBackgroundDrawable(getResources().getDrawable(
//R.drawable.deep2light));
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(255, 255, 0, 0)));
// 设置好参数之后再show
//popupWindow.showAsDropDown(view);
popupWindow.showAtLocation(rlStatusBar,Gravity.TOP,0,0);
popupWindow.setAnimationStyle(R.style.PopupAnimation);
popupWindow.setClippingEnabled(true);
popupWindow.update();
}