Android PopupWindow 自定义 Java 动画

Android PopupWindow Custom Java Animation

我想 show/hide 使用来自 this answer 的 expand/collapse 动画弹出窗口。 我可以通过将动画应用于弹出视图来使用动画,弹出视图是弹出窗口内的视图。我现在面临的问题是,当用户触摸弹出窗口外部时,弹出窗口会自动关闭,我无法在关闭弹出窗口之前显示折叠动画。

这是我写的代码:

View popupView = View.inflate(context,R.layout.popuplayout, null);
popup = new PopupWindow(popupView,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setAnimationStyle(0);
popup.setOutsideTouchable(true);
popup.setFocusable(true);
popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popup.showAsDropDown(anchor, 0, 0);
popup.setBackgroundDrawable(null);
popupView.post(new Runnable() {
    @Override
    public void run() {
            expand(popupView);
    }
});
.
.
.
private void expand(final View v) {
    final int targetHeight = ((View)v.getParent()).getHeight();
    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? LayoutParams.MATCH_PARENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };
    a.setDuration(200);
    v.startAnimation(a);
}

我想知道是否有一种方法可以在没有 xml 样式的情况下在关闭弹出窗口之前显示动画,或者使用 xml 动画实现给定的动画。

这是你应该做的,

1)创建两组不同的动画。

说,popup_show.xmlpopup_hide.xml 并将其添加到您的 anim 文件夹,您必须在 res 文件夹中创建该文件夹。

2)现在在 values 文件夹中创建一个名为 styles.xml 的 xml 并将这些动画添加到其中像这样,

<style name="Animation">
    <item name="android:windowEnterAnimation">@anim/popup_show</item>
    <item name="android:windowExitAnimation">@anim/popup_hide</item>
</style>

3)现在将此样式设置为您的 PopupWindow 动画,

 popup.setAnimationStyle(R.style.Animation);

现在它会自动检测 Window 进入和退出并提供所需的动画。 根据 Andro Selva 的说法。

public class PopupWindowCustom extends PopupWindow{
   public dismiss(){
     View view = getCustomView();
     expand(view);
     super.dismiss();
   }

   private expand(View view){
     //do some anim
   }
}