Thursday, November 12, 2015

Transition


In this tutorial we will take a look at the TransitionDrawable class, which lets us display a smooth cross-fade effect between two pictures.

Firstly, we'll need to add 2 pictures to the drawable directory of the project. In my case, they are sample1.jpg and sample2.jpg, and I put both of them in res/drawable-hdpi/ directory.

Add an xml file in the same directory, call it transition.xml. Here we will add a transition node with 2 item nodes inside, each representing an image:
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/d1"/>
    <item android:drawable="@drawable/d8"/>
</transition>




package com.example.trans;

import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;


public class MainActivity extends ActionBarActivity {
private ImageView image;
private TransitionDrawable trans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        image = (ImageView)findViewById(R.id.image);
        Resources res = this.getResources();
        trans = (TransitionDrawable)res.getDrawable(R.drawable.transition);
     
        image.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
        image.setImageDrawable(trans);
        trans.reverseTransition(1000);
        }
        });
    }

}


<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"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/d1"
        />
    
</LinearLayout>

No comments:

Post a Comment