最近做的android项目,需要实现弹出层,并灰掉弹出层后面的部分。大致需要做的效果为,点击more时,弹出一层只遮罩中间部分(由图一到图二),效果图如下(个人随便写的样式,勿怪哈),废话不说,直接上思路代码。
图一 图二
点击more,调用的代码
/** * 点击more触发的方法,弹出显示所有年级学科 * @param view */ public void showAllSubject(View view) { if (null == mPopupWindow) { View layout = LayoutInflater.from(this).inflate( R.layout.activity_allgrade, null); int width = subjectListView.getWidth(); int height = subjectListView.getHeight(); //设置弹出部分和面积大小 mPopupWindow = new PopupWindow(layout, width, height, true); //设置动画弹出效果 mPopupWindow.setAnimationStyle(R.style.PopupAnimation); // 设置半透明灰色 ColorDrawable dw = new ColorDrawable(0x7DC0C0C0); mPopupWindow.setBackgroundDrawable(dw); mPopupWindow.setClippingEnabled(true); } int[] pos = new int[2]; subjectListView.getLocationOnScreen(pos); mPopupWindow.showAtLocation(subjectListView, Gravity.RIGHT | Gravity.TOP, pos[0], pos[1]); }
弹出效果配置
<style name="PopupAnimation" parent="android:Animation"> <item name="android:windowEnterAnimation">@anim/popup_enter</item> <item name="android:windowExitAnimation">@anim/popup_exit</item> </style>
popup_enter.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <scale android:duration="100" android:fromXScale="1.0" android:fromYScale="0" android:pivotX="50%" android:pivotY="0%" android:toXScale="1.0" android:toYScale="1.0" /> </set>
popup_exit.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <scale android:duration="50" android:fromXScale="1.0" android:fromYScale="1.0" android:pivotX="50%" android:pivotY="0%" android:toXScale="1.0" android:toYScale="0" /> </set>
至此,主要代码完成。备注:popup_enter.xml和popup_exit.xml两个文件放在res下面的anim文件夹中,弹出层的页面没有贴代码,大家可以根据自己的需求来编写弹出页面的内容。