In this blog, We are going to show you how to shared element Image transition works in application.
To make a screen transition animation between two activities that have a shared element:
- Enable window content transitions in your theme.
- Specify a shared elements transition in your style.
- Define your transition as an XML resource.
- Assign a common name to the shared elements in both layouts with the
android:transitionName
attribute. - Use the
ActivityOptions.makeSceneTransitionAnimation()
method.
Implementation
Step 1: Add android:transitionName=”profile” in your ImageView
activity_main.java
1234567891011121314151617181920 <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"tools:context="application.coderdna.imageanimation.MainActivity"><ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:transitionName="profile"app:srcCompat="@mipmap/ic_launcher"tools:layout_editor_absoluteX="164dp"tools:layout_editor_absoluteY="129dp" /></LinearLayout>
Step 2: Add below code on your onClickListener,
12345 Intent intent = new Intent(view.getContext(), Main2Activity.class);View v = ((View) findViewById(R.id.imageView));ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, v, "profile");startActivity(intent, options.toBundle());
MainActivity.java
123456789101112131415161718 public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent(view.getContext(), Main2Activity.class);View v = ((View) findViewById(R.id.imageView));ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, v, "profile");startActivity(intent, options.toBundle());}});}}
Step 3: Add android:transitionName=”profile” in your ImageView in Result Activity,
12345678910 <ImageView xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:transitionName="profile"app:layout_behavior="@string/appbar_scrolling_view_behavior"app:srcCompat="@mipmap/ic_launcher"tools:context="application.coderdna.imageanimation.Main2Activity"tools:showIn="@layout/activity_main2">
Done, Now you have made your first shared element transition.