动画后冻结的布局子项

Layout children frozen after animation

我正在为屏幕外的 ConstraintLayout 设置动画,然后再返回屏幕。但是,在将 ConstraintLayout 动画化回视图后,子元素(EditTexts 和 Button)被冻结。

我认为这是因为布局只是显示其自身的图像,实际元素在后面。我怎样才能让布局达到 'redraw'?

这是问题的一个例子:

这是我的代码:

slide_out_left.xml:

 <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
        android:shareInterpolator="false" >
        <translate android:duration="200" android:fromXDelta="0%" android:toXDelta="-100%"/>
    </set>

slide_in_left.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="200" android:fromXDelta="-100%" android:toXDelta="0%"/>
</set>

查看代码:

public void slideCreateFormOutToLeft() {

    Animation slideOutLeft = AnimationUtils.loadAnimation(getActivityContext(), R.anim.slide_out_left);
    slideOutLeft.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            createTaskViewFormContainer.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });
    createTaskViewFormContainer.startAnimation(slideOutLeft);
}

public void slideCreateFormInFromLeft() {

    createTaskViewFormContainer.setVisibility(View.VISIBLE);
    Animation slideInLeft = AnimationUtils.loadAnimation(getActivityContext(), R.anim.slide_in_left);
    slideInLeft.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });
    createTaskViewFormContainer.startAnimation(slideInLeft);

}

由此Androiddocumentation

Another disadvantage of the view animation system is that it only modified where the View was drawn, and not the actual View itself. For instance, if you animated a button to move across the screen, the button draws correctly, but the actual location where you can click the button does not change, so you have to implement your own logic to handle this.

所以createTaskViewFormContainer里面的Buttons和EditTexts不在你的点击区域附近。这是ViewAnimation的问题,建议改用PropertyAnimation,像这样:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;

createTaskViewFormContainer.animate().translationX(-screenWidth).start();

要恢复视图:

createTaskViewFormContainer.animate().translationX(0).start();