View间渐变:

渐变动画(也叫消失)通常指渐渐地淡出某个UI组件,同时同步地淡入另一个。当APP想切换内容或View的情况下,这种动画很有用。渐变简短不易察觉,同时又提供从一个界面到下一个之间流畅的转换。如果在需要转换的时候没有使用任何动画效果,这会使得转换看上去感到生硬而仓促。

例子:
首先创建一个布局:

<FrameLayout xmlns:android="/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView xmlns:android="/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>

设置动画
1. 为我们想渐变的View创建成员变量
2. 对于被淡入的View设置它的visibility为GONE。这样防止view再占据局部的空间,而且也能在局部计算中将其忽略,加速处理
3. 将config_shortAnimTime系统属性暂存到一个成员变量里。这个属性为动画定义了一个标准的“短”持续时间。对弈细微遇快速发生的动画,这是个很理想的持续时段。也可以根据需要使用:
config_longAnimTime或config_mediumAnimTime。

public class CrossfadeActivity extends Activity {

    private View mContentView;
    private View mLoadingView;
    private int mShortAnimationDuration;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crossfade);

        mContentView = findViewById(R.id.content);
        mLoadingView = findViewById(R.id.loading_spinner);

        // Initially hide the content view.
        mContentView.setVisibility(View.GONE);

        // Retrieve and cache the system's default "short" animation time.
        mShortAnimationDuration = getResources().getInteger(
                android.R.integer.config_shortAnimTime);
    }

对于正在淡入的View,设置它的alpha值为0,并且设置visibility为VISIBLE,这样view就可可见,但是此时为透明的。
对于正在淡入的View,把alpha值从0动态改变到1。同时,对于淡出的View,把alpha值从1动态变到0。
使用Animator.AnimatorListener中的 onAnimationEnd(),设置淡出View的visibility为GONE。即使alpha值为0,也要把View的visibility设置成GONE来防止 view 占据布局空间,还能把它从布局计算中忽略,加速处理过程。

private void crossfade() {

    // Set the content view to 0% opacity but visible, so that it is visible
    // (but fully transparent) during the animation.
    mContentView.setAlpha(0f);
    mContentView.setVisibility(View.VISIBLE);

    // Animate the content view to 100% opacity, and clear any animation
    // listener set on the view.
    mContentView.animate()
            .alpha(1f)
            .setDuration(mShortAnimationDuration)
            .setListener(null);

    // Animate the loading view to 0% opacity. After the animation ends,
    // set its visibility to GONE as an optimization step (it won't
    // participate in layout passes, etc.)
    mLoadingView.animate()
            .alpha(0f)
            .setDuration(mShortAnimationDuration)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoadingView.setVisibility(View.GONE);
                }
            });
}

只用ViewPager实现屏幕滑动

屏幕滑动是两个完整界面间的转换。
首先创建View:

创建Fragment所使用的布局文件:

<!-- fragment_screen_slide_page.xml -->
<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:padding="16dp"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/lorem_ipsum" />
</ScrollView>

ScrollView是一个滚动视图的容器

然后创建一个Fragment的子类,让它从onCreateView()方法中返回之前创建的布局:

import android.support.v4.app.Fragment;
...
public class ScreenSlidePageFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_screen_slide_page, container, false);

        return rootView;
    }
}

添加ViiewPage
Viewpage有内建的滑动手势用来在页面间转换,并且它默认使用滑屏动画,所以我们不用自己为其创建。ViewPage使用PagerAdapter来补充新页面,所以PagerApter会用到你之前新建的Fagment类。

<!-- activity_screen_slide.xml -->
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

创建一个Activity来做下面的事情:

  • 把ContentView设置成这个包含Viewpager的布局。
  • 创建一个继承自FragmentStatePagerAdapter抽象类,然后实现getItem()方法来把ScreenSlidePageFragment实例作为新羽绒棉补充进来。PagerAdater还需要实现getCount()方法。返回Adapter将要创建页面的总数。
  • 把PagerAdapter和ViewPager关联起来。
  • 处理Back阿牛,按下变为在虚拟的Fragment栈中回退。如果用户已经在第一个页面,则在Activity的回退栈中回退。
public class ScreenSlidePagerActivity extends FragmentActivity {
    /**
     * The number of pages (wizard steps) to show in this demo.
     */
    private static final int NUM_PAGES = 5;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_slide);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    /**
     * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
     * sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new ScreenSlidePageFragment();
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}

用PageTransformer自定义动画

要展示不同于默认滑屏效果的动画,我们需要实现ViewPager.PageTransformer接口,然后把它补充到ViewPager里。这个接口只暴露了一个方法。transformPage()。每次界面切换这个方法都会为每个可见页面和刚消失的相邻页面调用一次。
在transformPage()的实现中,基于当前屏幕显示的页面的position(position 由transformPage()方法的参数给出)决定哪些页面需要被动画转换,这样我们就能创建自己的动画。

position参数表示特定页面相对于屏幕中的页面的位置。它的值在用户滑动页面过程中动态变化。当某一页面填充屏幕,它的值为0。当页面刚向屏幕右侧方向被拖走,它的值为1。如果用户在页面1和页面2间滑动到一半,那么页面1的position为-0.5并且页面2的position为 0.5。根据屏幕上页面的position,我们可以通过setAlpha(),setTranslationX()或setScaleY()这些方法设定页面属性来自定义滑动动画。
当我们实现了PageTransformer后,用我们的实现调用setPageTransformer()来应用这些自定义动画。例如,如果我们有一个叫做ZoomOutPageTransformer的PageTransformer,可以这样设置自定义动画:

ViewPager mPager = (ViewPager) findViewById(R.id.pager);
...
mPager.setPageTransformer(true, new ZoomOutPageTransformer());