1、说明
我们有时需要定义底部弹窗,比如做一个分享到QQ、微信、微博的底部选择弹窗。
2、实现方法
public class SharePopWindow extends PopupWindow {
private Activity mContext;
private WindowManager.LayoutParams windowLayoutParams;
public SharePopWindow(Activity context) {
super(context);
mContext = context;
windowLayoutParams = context.getWindow().getAttributes();
initView();
initListener();
}
/**
* 直接展示在屏幕底部,无需添加其它参数
*/
public void show() {
showAtLocation(mContext.getWindow().getDecorView(), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
setAlpha(0.5f);
}
private void initView() {
View v = View.inflate(mContext, R.layout.view_share_pop, null);
setContentView(v);
setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setFocusable(true);
// 底部弹出动画效果
setAnimationStyle(R.style.BottomInBottomOut);
// 设置背景色,保证弹窗主体没有黑边
ColorDrawable dw = new ColorDrawable(0xb0000000);
setBackgroundDrawable(dw);
}
private void initListener() {
setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
setAlpha(1.0f);
}
});
}
private void setAlpha(float alpha) {
windowLayoutParams.alpha = alpha;
mContext.getWindow().setAttributes(windowLayoutParams);
}
}
style.xml
<resources>
<!--底部弹窗-->
<style name="BottomInBottomOut" parent="android:Animation">
<item name="android:windowEnterAnimation">@anim/push_bottom_in</item>
<item name="android:windowExitAnimation">@anim/push_bottom_out</item>
</style>
</resources>
push_bottom_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="500"
android:fromYDelta="100%p"
android:toYDelta="0" />
</set>
push_bottom_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="500"
android:fromYDelta="0"
android:toYDelta="100%p" />
</set>
搞定 !