两个控件的交叉淡入淡出

来源:互联网 发布:屏幕数据库 编辑:程序博客网 时间:2024/04/30 08:33
原文链接:


http://developer.android.com/training/animation/crossfade.html#setup

交叉淡入动画,也就是融入动画,是指当一个控件进入场景的同时,另一个控件退出场景。当你在应用中需要切换内容时,这个动画十分的奏效。交叉动画可以说是小而精,但是它为从一个场景到另一个场景提供十分流畅的切换。然而,当你不用它时,你会发现,切换变得十分的迟钝或者仓促。

下面是一个例子,他展现的从进度条到文本的平滑切换。



创建视图(Create the Views)


创建两个你希望进行交叉动画的控件。下面以圆形进度条和文本控件为例。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"        android:id="@+id/content"        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView style="?android:textAppearanceMedium"            android:lineSpacingMultiplier="1.2"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="@string/lorem_ipsum"            android:padding="16dp" />    </ScrollView>    <ProgressBar android:id="@+id/loading_spinner"        style="?android:progressBarStyleLarge"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center" /></FrameLayout>

建立动画(Set up the Animation)


建立动画的步骤:

  1. 创建若干个你希望进行淡入淡出的View对象。当你在操作这些View对象时,需要引用它们。
  2. 对于那个淡入的对象,设置它的visibility属性为GONE. 这主要是为了防止该view对象占据Layout的空间,在layout时忽略它,加速布局的速度。
  3. 使用系统变量config_shortAnimTime 作为View对象的动画时长。这个变量是动画中的标准短间隔。这个间隔时对于频繁的动画是十分理想的。当然你也可以使用config_longAnimTime 和 config_mediumAnimTime

这里有一个例子,Here's an example using the layout from the previous code snippet as the activity content view:



淡入淡出View(Crossfade the Views)


如果要让View淡入淡出,需要做如下几步:

  1. 设置淡入的View,其透明度为0,visibility为VISIBLE. (之前它设置为GONE.) 。这主要是为了使View可见但是完全透明。
  2. 对于淡入的View,其动画的透明度从0变为1;对于淡出的View,其动画的透明度从1变为0。
  3. 补充 Animator.AnimatorListener中的onAnimationEnd()方法 , 设置淡出的View可见性为 GONE.虽然淡出的View透明度为0,但是设置可见性为 GONE可以 在layout时忽略它,加速布局的速度。

下面是一小段代码:

private View mContentView;private View mLoadingView;private int mShortAnimationDuration;...private void crossfade() {    //设置内容View的Alpha值为0,可见性为VISIABLE    mContentView.setAlpha(0f);    mContentView.setVisibility(View.VISIBLE);    // 设置内容View的动画效果    mContentView.animate()            .alpha(1f)            .setDuration(mShortAnimationDuration)            .setListener(null);    // 当动画结束时,设置载入View的可见性为GONE.    mLoadingView.animate()            .alpha(0f)            .setDuration(mShortAnimationDuration)            .setListener(new AnimatorListenerAdapter() {                @Override                public void onAnimationEnd(Animator animation) {                    mLoadingView.setVisibility(View.GONE);                }            });}


0 0
原创粉丝点击