如何在数据适合屏幕时停止运动布局动画

How to Stop Motion Layout animation when data is fit to screen

我将 Motion Layout 用于 Collapse Layout。运动布局非常适合我的需要,但我想根据适合屏幕的数据设置运动布局动画。

就像如果数据适合屏幕就不需要动画。如果数据超出屏幕则显示动画。

终于找到解决方案:

motionLogin?.enableTransition(R.id.transitionLogin, false)
        constraintLayout.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {

            override fun onGlobalLayout() {
                // If the scrollView can scroll, disable the accept menu item button
                if (constraintLayout.canScrollVertically(1) || constraintLayout.canScrollVertically(
                        -1
                    )
                ) {
                    motionLogin?.enableTransition(R.id.transitionLogin, true)
                }

                // Remove itself after onGlobalLayout is first called or else it would be called about a million times per second
                constraintLayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

对于 Java 版本:

 public static void enableDisableTransition(MotionLayout motionLayout, RecyclerView recyclerView){
    motionLayout.enableTransition(R.id.transition, false);
    recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (recyclerView.canScrollVertically(1) || recyclerView.canScrollVertically(-1 )
            ) {
                motionLayout.enableTransition(R.id.transition, true);
            }
            recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
}