Saturday, September 17, 2016

Animation/ Interpolator in Android - Bouncing Ball

Hi .... Dear All ....  Today I am uploading a superb example of Bouncing Ball.
In this example i use Bouncing Interpolator to add animation.

Interpolator 

• Interpolation is rate of change of the animation.
• The animation framework needs to know how to calculate the current state of the View or Object at any instant of time.
• Interpolators define this property that lets animation classes calculate the state of a view.
• Interpolators are animation defined in XML.
• Animation effects can be repeated, accelerated, decelerated, bounced etc.
• Every animation needs an interpolator
Interpolators are separate classes that control animations

A. The output will be 


B.  XML file 

<?xml version="1.0" encoding="utf-8"?>

<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="com.exam.ravi.animexppt.Main2Activity">
    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:id="@+id/the_button"

        android:text="Bounce Ball" ></Button>

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageView"

        android:layout_gravity="center_horizontal"

        android:src="@drawable/ball" />

 </LinearLayout>

C. Java Code 

package com.exam.ravi.animexppt;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;


public class Main2Activity extends AppCompatActivity  implements View.OnClickListener 
{
    Button button;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        button = (Button) findViewById(R.id.the_button);
        button.setOnClickListener(this);
    }

    @Override

    public void onClick(View v) {
        ImageView  img  = (ImageView) findViewById(R.id.imageView);
        img.clearAnimation();
        TranslateAnimation translation;
        translation = new TranslateAnimation(0f, 0f, 0f,600f);
        translation.setDuration(2000);
        translation.setFillAfter(true);
        translation.setInterpolator(new BounceInterpolator());
        img.startAnimation(translation);
    }

}

No comments:

Post a Comment