Android RecyclerView平滑滚动以查看其动画高度

时间:2015-01-19 13:12:33

标签: java android android-animation android-recyclerview android-scroll

我有一个带有可扩展子视图的RecyclerView,当单击子ViewGroup时,它会将ViewGroup高度的视图数量从0增加到测量的视图组高度,如下面的gif所示:

example

问题是:我在recyclerView上调用smoothScrollToPosition,它平滑滚动到视图位置,但是它考虑了当前视图高度,这仍然没有扩展,在上面的gif中我正在触摸下面的视图recyclerview,由于视图已经可见,因此无法滚动到位置,但当我再次触摸时(再次调用smoothscrolltoposition),它会将视图滚动到正确的位置,因为视图已经展开。

有没有办法将视图滚动到屏幕顶部或只是滚动以使内容可见?

供参考: 这是调用视图的方法:

collapsible_content.removeAllViews();
for(int i = 0; i < 5; i++) {
        View link_view = getLayoutInflater().inflate(R.layout.list_item_timeline_step_link, collapsible_content, false);
        TextView text = (TextView) link_view.findViewById(R.id.step_link_text);
        text.setText("Test");
        collapsible_content.addView(link_view);
    }

这是我扩展的方法:

public void toggle() {
        collapsible_content.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        Animation a;
        if (mExpanded) {
            a = new ExpandAnimation(collapsible_content.getLayoutParams().height, 0);
        } else {
            a = new ExpandAnimation(collapsible_content.getLayoutParams().height, getMeasuredHeight());
        }
        a.setDuration(mAnimationDuration);
        collapsible_content.startAnimation(a);
        mExpanded = !mExpanded;
    }

动画:

private class ExpandAnimation extends Animation {
        private final int mStartHeight;
        private final int mDeltaHeight;

        public ExpandAnimation(int startHeight, int endHeight) {
            mStartHeight = startHeight;
            mDeltaHeight = endHeight - startHeight;
        }

        @Override
        protected void applyTransformation(float interpolatedTime,
                                           Transformation t) {
            final int newHeight = (int) (mStartHeight + mDeltaHeight *
                    interpolatedTime);
            collapsible_content getLayoutParams().height = newHeight;

            if (newHeight <= 0) {
                collapsible_content setVisibility(View.GONE);
            } else {
                collapsible_content setVisibility(View.VISIBLE);
            }
            collapsible_content requestLayout();
        }


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

2 个答案:

答案 0 :(得分:7)

我的解决方案是在applyTransformation方法中不断检查视图底部,并将其与RecyclerView高度进行比较,如果底部高于RV高度,我会按差异值滚动:

final int bottom = collapsible_content.getBottom();
final int listViewHeight = mRecyclerView.getHeight();
if (bottom > listViewHeight) {
    final int top = collapsible_content.getTop();
    if (top > 0) {
        mRecyclerView.smoothScrollBy(0, Math.min(bottom - listViewHeight + mRecyclerView.getPaddingBottom(), top));
    }
}

诀窍是使用Math.min将视图置于顶部,因此不要向上滚动使顶部不可见。

基于ListViewAnimations

的解决方案

答案 1 :(得分:0)

添加animationlistener并在展开动画完成后开始滚动recyclelerview。

相关问题