android开发--activity间的转场动画示例

先上一个效果图:

如何所示的动画效果示意图,经常在某些app上会遇到吧,这就是activity间的转场动画,下面贴出代码:

看图就知道这里有两个activity,以及对应的两个布局文件,第一个布局文件及activity如下:




    

        

        
    

    

        

        

    

import android.app.ActivityOptions;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.Explode;
import android.transition.Transition;
import android.util.Pair;
import android.view.View;

import com.example.animation.R;

public class FirstActivity extends AppCompatActivity {

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

    public void onClick(View view) {
        int resId = -1;
        switch (view.getId()) {
            case R.id.iv1:
                resId = R.drawable.pic1;
                break;
            case R.id.iv2:
                resId = R.drawable.pic2;
                break;
            case R.id.iv3:
                resId = R.drawable.pic3;
                break;
            case R.id.iv4:
                resId = R.drawable.pic4;
                break;
        }
        Intent intent = new Intent(this,SecondActivity.class);
        intent.putExtra("resId",resId);
        Transition transition = new Explode();
        transition.excludeTarget(android.R.id.statusBarBackground,true);

        getWindow().setEnterTransition(transition);
        getWindow().setExitTransition(transition);
        getWindow().setReenterTransition(transition);

        Pair shareElement = Pair.create(view,"img");
        ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,shareElement);
        startActivity(intent,options.toBundle());
    }
}

布局也不复杂,就是四张图,当点击对应图的时候需要设置resId,这个resId会传到下一个activity中用于把对应的图片展示出来,excludeTarget()方法用于把状态栏排除在动画效果之外,就是让状态栏固定,不跟着整个画面一起变动;Pair的那行代码就是设置共享元素,让点击的那张图和对应放大了的图之间的过渡有个视觉连续性

接下来是第二个activity和布局文件:




    

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.Explode;
import android.transition.Transition;
import android.widget.ImageView;

import com.example.animation.R;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        int resId = getIntent().getExtras().getInt("resId");
        ImageView iv = (ImageView) findViewById(R.id.iv);
        iv.setImageResource(resId);

        Transition transition = new Explode();
        transition.excludeTarget(android.R.id.statusBarBackground,true);
        getWindow().setEnterTransition(transition);
        getWindow().setExitTransition(transition);
    }

}

代码很简单,没啥需要说的,就这么轻轻松松的就实现了这个转场动画的效果

你可能感兴趣的:(android开发--activity间的转场动画示例)