使用RecyclerView中的动画将setVisibility从Gone变为Visible

时间:2017-04-26 08:05:18

标签: java android

我的android项目中有RecyclerView,每行有2 LinearLayout。 首先,我希望其中一个布局已经过去了。点击行后,它会通过动画显示出来。简而言之,我想在没有任何外部库的情况下实现可扩展的RecyclerView。你能给我一个解决方案吗? 我想通过动画hoder.itemView的高度来实现这一目标。但实际上我并不知道要插入什么而不是????,因为起初我并不知道它的高度。

if(holder.layout2.getVisibility() == View.Gone) {
            holder.layout2.setVisibility( View.VISIBLE );
            animateHeight(holder.itemView,?????);
        }
        else {
            animateHeight(holder.itemView,holder.itemView.getHeight - holder.layout2.getHeight());
            holder.layout2.setVisibility( View.GONE );
        }

public void animateHeight(final View v, final int height) {

    final int initialHeight = v.getMeasuredHeight();
    int duration = 500;
    Interpolator interpolator = new AccelerateInterpolator();

    // I have to set the same height before the animation because there is a glitch
    // in the beginning of the animation
    v.getLayoutParams().height = initialHeight;
    final int diff = height - initialHeight;
    v.requestLayout();

    Animation a = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = initialHeight + (int) (diff * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    a.setDuration(duration);
    a.setInterpolator(interpolator);
    v.startAnimation(a);
}

1 个答案:

答案 0 :(得分:0)

在你的视图持有者类中做这样的事情来获得每个孩子的身高,

itemView.getViewTreeObserver().addOnGlobalLayoutListener( 
    new OnGlobalLayoutListener(){

        @Override
        public void onGlobalLayout() {

            mHeight = mView.getHeight();
            mView.getViewTreeObserver().removeGlobalOnLayoutListener( this );
            mView.setVisibility( View.GONE );
        }

});

这将是扩展模式下孩子的高度,稍后当您尝试为视图设置动画时,可以使用它。

相关问题