内推
【长期有效】欢迎加入字节跳动我的团队:内推链接
近阵子完成公司需求,在进行动画时,将View移出父布局,View被裁剪或者消失。
后来发现clipChildren属性可以解决这个问题。
示例如下:
1.首先看一个布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@android:color/holo_green_light"
android:orientation="vertical">
<TextView
android:id="@+id/txt_android"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@android:color/holo_red_light"
android:gravity="center"
android:text="Android"
android:textSize="50sp" />
</LinearLayout>
</LinearLayout>
理所当然,效果如下,TextView被裁剪了:
而当我们稍微修改一点,在最外层LinearLayout上加上android:clipChildren="false"时,效果就变了。(clipChildren属性默认是true)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@android:color/holo_green_light"
android:orientation="vertical">
<TextView
android:id="@+id/txt_android"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@android:color/holo_red_light"
android:gravity="center"
android:text="Android"
android:textSize="50sp" />
</LinearLayout>
</LinearLayout>
效果如下:
很神奇,超过父布局的内容显示出来了。
然后演示下动画:
布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:orientation="vertical"
android:weightSum="2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@android:color/holo_green_light"
android:orientation="vertical">
<TextView
android:id="@+id/txt_android"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@android:color/holo_red_light"
android:gravity="center"
android:text="Android"
android:textSize="50sp" />
</LinearLayout>
</LinearLayout>
动画代码如下:
ObjectAnimator animator = ObjectAnimator.ofFloat(mTextView, "y", 0, 800);
animator.setDuration(5000);
animator.start();
效果如下:
Tips:你可能会发现,我将View移出了父布局,但是我是在爷爷布局设置的clipChildren属性,这个我暂时也没弄太明白,但是是亲测,只有在爷爷布局设置才能生效。
注意:发现一个bug,部分4.2.2的手机上,如果此view的动画超过其父布局进入爷爷布局,会出现view的部分内容在爷爷布局中残留的问题!!!