Switch between views with crossfade animation

后端 未结 2 1421
日久生厌
日久生厌 2021-02-15 16:43

I\'ve wrote a small activity that is able to switch between two views. Now I am trying to add some animation (fade-in/fade-out effect). Can anybody explain me how to do that rig

相关标签:
2条回答
  • 2021-02-15 17:12

    I think there are 2 main solution to this problem

    • The first one is using a ViewFlipper as suggested.
    • The other one is to go with the solution described here.

    I prefer the second one cause it doesn't need additional View object in your view hiearchy and second you can have your 2 view all across the view tree. Not only in a single place defined by the position of the ViewFlipper.

    0 讨论(0)
  • 2021-02-15 17:33

    The way I have done this in the past is by using the ViewFlipper class and utilizing the built-in animation functions that the package provides.

    Here is an example on how to do this; in my experience the transitions have been very smooth:

    The XML File

    <LinearLayout
        //Ommitted...
        <ViewFlipper
            android:id="@+id/[your_id_here]"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
                <RelativeLayout
                    <!--Your first layout XML here...-->
                </RelativeLayout>
                <RelativeLayout
                    <!--Your second layout XML here...-->
                </RelativeLayout>
        </ViewFlipper>
    </LinearLayout>
    

    Please note that you do not have to use relative layouts, I simply used them for the sake of clarity.

    Implementing The Animations

    Get a reference to the ViewFlipper in your activity:

    ViewFlipper v = (ViewFlipper) findViewById(R.id.[your_id]);
    

    Set the animations as necessary:

    v.setInAnimation(AnimationUtils.loadAnimation([your_activity_name].this, R.anim.[your_in_animation here]));
    v.setOutAnimation(AnimationUtils.loadAnimation([your_activity_name].this, R.anim.[your_out_animation here]));
    

    Please note that you can find some really good prebuilt animations in the Android class files located in the following directory:

    [android-sdks]/samples/android-[VERSION_NUMBER_HERE]/ApiDemos/res/anim
    

    I highly recommend using these if you can - it will save you much time.

    Now, if you wish to switch between the views, use the following commands:

    v.showNext();
    v.showPrevious();
    

    You might have to change the animation files slightly to make sure the animations transition properly (i.e. make a fade right and left animation).

    Hope this helps!

    0 讨论(0)
提交回复
热议问题