Add a transition or cross-fade between two images
suggest changeStep 1: Create a transition drawable in XML
Save this file transition.xml in res/drawable folder of your project.
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image1"/>
<item android:drawable="@drawable/image2"/>
</transition>
image1 and image2 are the two images to transition. Put them in res/drawable as well.
Step 2: Add an ImageView that will show the transition
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image1"/>
</LinearLayout>
Step 3: Load the transition drawable and start it from a click listener
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image_view);
transitionDrawable = (TransitionDrawable)
ContextCompat.getDrawable(this, R.drawable.transition);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
imageView.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(1000);
}
});
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents