最近在写类似于美团的底部弹出购物车使用popupWindow来实现。
先讲解动画:在res/下新建一个文件夹anim,进而anim下新建两个xml文件,如图所示:
其中,pophidden_anim的代码如下
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="1000" android:fromYDelta="0" android:toYDelta="50%p" /> <alpha android:duration="1000" android:fromAlpha="1.0" android:toAlpha="0.0" /> </set>
popshow_anim的代码如下
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="1000" android:fromYDelta="100%p" android:toYDelta="0" /> <alpha android:duration="1000" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set>
然后在values/styles.xml加入以下代码,变成这个样子,上面的那些是自带的
<resources> <!-- Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. --> <style name="AppBaseTheme" parent="android:Theme.Light"> <!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. --> </style> <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> <!-- 这个是加入的代码 --> <style name="mypopwindow_anim_style"> <item name="android:windowEnterAnimation">@anim/popshow_anim</item> <!-- 指定显示的动画xml --> <item name="android:windowExitAnimation">@anim/pophidden_anim</item> <!-- 指定消失的动画xml --> </style> </resources>代码中popupWindow使用:
popupWindow.setAnimationStyle(R.style.vegetable_pop);加载
刚开始在自定义View中要获取popUpWindow的高度一直不成功,最后修改如下
public class VegetableCarsWindow { private LayoutInflater inflater; private Activity context; private PopupWindow popupWindow; private View contentView; //显示的视图 public VegetableCarsWindow(Activity context){ this.context=context; inflater=context.getLayoutInflater(); contentView=inflater.inflate(R.layout.vegetable_popwindow, null); initView(); } public void initView(){ popupWindow=new PopupWindow(contentView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(true); popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.setAnimationStyle(R.style.vegetable_pop); popupWindow.setFocusable(true); contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); } public void setShow(View view){ int[] location = new int[2]; view.getLocationOnScreen(location); popupWindow.showAtLocation(view, Gravity.TOP, 0, location[1]-contentView.getMeasuredHeight()); //显示 } }红色部分是关键