Android: Expand/collapse animation

后端 未结 30 2464
说谎
说谎 2020-11-22 05:01

Let\'s say I have a vertical linearLayout with :

[v1]
[v2]

By default v1 has visibily = GONE. I would like to show v1 with an expand animat

30条回答
  •  無奈伤痛
    2020-11-22 05:36

    You can use a ViewPropertyAnimator with a slight twist. To collapse, scale the view to a height of 1 pixel, then hide it. To expand, show it, then expand it to its height.

    private void collapse(final View view) {
        view.setPivotY(0);
        view.animate().scaleY(1/view.getHeight()).setDuration(1000).withEndAction(new Runnable() {
            @Override public void run() {
                view.setVisibility(GONE);
            }
        });
    }
    
    private void expand(View view, int height) {
        float scaleFactor = height / view.getHeight();
    
        view.setVisibility(VISIBLE);
        view.setPivotY(0);
        view.animate().scaleY(scaleFactor).setDuration(1000);
    }
    

    The pivot tells the view where to scale from, default is in the middle. The duration is optional (default = 1000). You can also set the interpolator to use, like .setInterpolator(new AccelerateDecelerateInterpolator())

提交回复
热议问题