一、初始化父View和子View
onCreate(Bundle SavedInstanceState){
super.onCreate(SavedInstanceState)
setContentView(R.layout.activity_good_rank_list);
viewParent = getLayoutInflater().inflate(R.layout.activity_good_rank_list, null);
viewContent = getLayoutInflater().inflate(R.layout.popup_sort, null);
//pop用子view来呈现,后面两个参数分别是宽和高
popupWindow = new PopupWindow(viewContent, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
二、为pop设置动画
<resources>
<style name="animation">
<item name="android:windowEnterAnimation">@anim/enter</item>
<item name="android:windowExitAnimation">@anim/out</item>
</style>
</resources>```
enter:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate
android:duration="500"
android:fromYDelta="100%p"
android:toYDelta="0" />
<alpha
android:duration="300"
android:fromAlpha="0.0"
android:toAlpha="1.0" />
</set>```
out:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate
android:duration="500"
android:fromYDelta="0"
android:toYDelta="100%p" />
<alpha
android:duration="300"
android:fromAlpha="1.0"
android:toAlpha="0" />
</set>```
//给popupWindow窗口加入动画效果
popupWindow.setAnimationStyle(R.style.animation);```
三、展现pop
//显示PopupWindow的方法:
showAsDropDown(Viewanchor) //相对某个控件的位置(正下方),无偏移 , 有滑动出来的效果
showAsDropDown(Viewanchor, int xoff, int yoff) //相对某个控件的位置,有偏移,xoff X轴的偏移量,yoff Y轴的偏移量
showAtLocation(Viewparent, int gravity, int x, int y) //在父容器的什么位置,gravity为相对位置,如:正中央Gravity.CENTER、下方Gravity.BOTTOM、Gravity.Right|Gravity.BOTTOM右下方等,后面两个参数为x/y轴的偏移量。```
####四、pop外部点击可以取消
// 点击空白的地方关闭PopupWindow
有两种方案
//此方案外部点击取消的同时,如果点击到外部的控件,会产生点击效果
popupWindow.setBackgroundDrawable(new BitmapDrawable());//加背景
popupWindow.setOutsideTouchable(true);//设置外部点击取消```
//此方案点击外部只会取消,在popupWindow show出来之前设置
popupWindow.setBackgroundDrawable(new BitmapDrawable());//加背景
popupWindow.setFocusable(true);//设置外部点击取消```
####五、弹出pop改变背景颜色
只需在弹出后增加改变背景颜色的代码
backgroundAlpha(0.5f);```
//方法具体代码
void backgroundAlpha(float bgAlpha){
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgAlpha; //0.0-1.0
getWindow().setAttributes(lp);
}```
//当然在pop消失时需要恢复背景色,此时需要监听pop的消失事件
popupWindow.setOnDismissListener(new OnDismissListener){
@Override
public void onDismiss() {
backgroundAlpha(1);
}
}```