Search code examples
androidanimationandroid-popupwindow

Android PopupWindow Custom Java Animation


I want to show/hide a popupwindow using a expand/collapse animation from this answer. I was able to use the animation by applying it to the popup view which is a view inside popupwindow. The problem I'm facing now is that when user touches outside popupwindow, popupwindow automatically dismisses and I cannot show collapse animation before dismissing the Popup.

Here is the code I have written:

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);
}

I was wondering whether there is a way to show an animation before dismissing popup on touching outside without xml style or implement the given animation using xml animations.


Solution

  • public class PopupWindowCustom extends PopupWindow{
       public dismiss(){
         View view = getCustomView();
         expand(view);
         super.dismiss();
       }
    
       private expand(View view){
         //do some anim
       }
    }