Category Archives: Animation

Simple way to Animating Layout Changes in Android.

A layout animation is a pre-loaded animation that the system runs each time you make a change to the layout configuration. All you need to do is set an attribute in the layout to tell the Android system to animate these layout changes, and system-default animations are carried out for you.

    Create the Layout

In your activity’s layout XML file, set the android:animateLayoutChanges attribute to true for the layout that you want to enable animations for. For instance:

<LinearLayout android:id="@+id/container"
    android:animateLayoutChanges="true"
    ...
/>
    Add, Update, or Remove Items from the Layout

Now, all you need to do is add, remove, or update items in the layout and the items are animated automatically:

private ViewGroup mContainerView;
...
private void addItem() {
    View newView;
    ...
    mContainerView.addView(newView, 0);
}

Here is the complete sample layout file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/container"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
    android:animateLayoutChanges="true">

    <Button
        android:id="@+id/buttonAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Views" />

     <Button
        android:id="@+id/buttonRemove"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remove Views" />
     
</LinearLayout>

The MainActivity file.

package com.coderzheaven.demo1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	LinearLayout mContainerView;
	int id = 0;

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

		mContainerView = (LinearLayout) findViewById(R.id.container);
		Button click = (Button) findViewById(R.id.buttonAdd);
		click.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				addView();
			}
		});
		Button remove = (Button) findViewById(R.id.buttonRemove);
		remove.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				removeView();
			}
		});
	}

	void addView() {
		Button b = new Button(this);
		b.setId(id++);
		b.setText("Button " + id);
		mContainerView.addView(b, 0);
	}

	void removeView() {

		View v = (View) findViewById(id - 1);
		if (v != null) {
			id--;
			v.setVisibility(View.GONE);
		}
	}
}

Just try with a sample layout and see the magic.

How to create a fully customizable Toast which will use your own time duration and gravity and layout with ease without using the default toast in android?

Hello all
We all have seen toasts right…ok then you have already customized your toasts right.

Here I will show you a method to create toasts which will last the time you set and the gravity.

You can download the code by clicking on the download links.

Custom Toast

This is the class that creates the toast notification.

MyMsgBox.java

package com.example.messageboxtest;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyMsgBox {

	private static final int ANIMATION_DURATION = 600;

	private int HIDE_DELAY = 5000;

	private View mContainer;

	private int gravity = Gravity.CENTER;

	private TextView mTextView;

	private Handler mHandler;

	private AlphaAnimation mFadeInAnimation;

	private AlphaAnimation mFadeOutAnimation;

	public MyMsgBox(Context context, int HIDE_DELAY, int gravity) {
		ViewGroup container = (ViewGroup) ((Activity) context)
				.findViewById(android.R.id.content);
		View v = ((Activity) context).getLayoutInflater().inflate(
				R.layout.newmb__messagebar, container);
		this.HIDE_DELAY = HIDE_DELAY;
		this.gravity = gravity;
		init(v);
	}

	private void init(View v) {
		mContainer = v.findViewById(R.id.mbContainer);
		mContainer.setVisibility(View.GONE);
		mTextView = (TextView) v.findViewById(R.id.mbMessage);
		mFadeInAnimation = new AlphaAnimation(0.0f, 1.0f);
		mFadeOutAnimation = new AlphaAnimation(1.0f, 0.0f);
		mFadeOutAnimation.setDuration(ANIMATION_DURATION);
		mFadeOutAnimation
				.setAnimationListener(new Animation.AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						mContainer.setVisibility(View.GONE);
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}
				});

		mHandler = new Handler();

	}

	public void show(String message) {
		mContainer.setVisibility(View.VISIBLE);

		((LinearLayout) mContainer).setGravity(gravity
				| Gravity.CENTER_VERTICAL);

		mTextView.setText(message);

		mFadeInAnimation.setDuration(ANIMATION_DURATION);

		mContainer.startAnimation(mFadeInAnimation);
		mHandler.postDelayed(mHideRunnable, HIDE_DELAY);
	}

	private final Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mContainer.startAnimation(mFadeOutAnimation);
		}
	};

}

Now the layout for this toast.. Here I am making a toast with only one textview in it.

This is the layout.
newmb__messagebar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mbContainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="10dp"
    android:gravity="bottom"
    android:orientation="vertical" >

    <LinearLayout
        style="@style/bgTheme"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="bottom"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/mbMessage"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Test"
            android:textColor="@drawable/white" />
    </LinearLayout>

</LinearLayout>

This will create some errors.
inside your drawable folder create an xml named “bg_gradiant.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><shape>
            <solid android:color="@drawable/dark_grey" />

            <stroke android:width="0dp" android:color="#000000" />

            <corners android:radius="5dp" />
        </shape></item>

</selector>

And at last in your values/styles.xml add this style

 <style name="bgTheme">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_gravity">center_horizontal|center</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@drawable/white</item>
        <item name="android:textStyle">bold</item>
        <item name="android:layout_margin">3dp</item>
        <item name="android:background">@drawable/bg_gradiant</item>
        <item name="android:textSize">14sp</item>
        <item name="android:typeface">normal</item>
        <item name="android:text">05</item>
        <item name="android:padding">10dp</item>
    </style>
[/xml

You can add these colors to your <strong>strings.xml</strong>
1
    <drawable name="white">#ffffff</drawable>
    <drawable name="black">#000000</drawable>
    <drawable name="blue">#2554C7</drawable>
    <drawable name="green">#347C2C</drawable>
    <drawable name="orange">#ff9900</drawable>
    <drawable name="pink">#FF00FF</drawable>
    <drawable name="violet">#a020f0</drawable>
    <drawable name="grey">#778899</drawable>
    <drawable name="red">#C11B17</drawable>
    <drawable name="yellow">#FFFF8C</drawable>
    <drawable name="PowderBlue">#b0e0e6</drawable>
    <drawable name="brown">#2F1700</drawable>
    <drawable name="Hotpink">#7D2252</drawable>
    <drawable name="dark_grey">#424242</drawable>

Now in your activity call the class like this.

// time in ms
MyMsgBox m = new MyMsgBox(arg0.getContext(), 5000,
		Gravity.BOTTOM);
m.show("Hello this is a custom toast");

Our custom toast is complete, now run the project and customize it according to your need.

You can download the complete android source code for this project from here.

Use of custom animations in a FragmentTransaction when pushing and popping a stack. or How to apply animations in Fragments when pushing on to a stack?

Hello all

We have seen many examples of how to use fragments in android.
You can search coderzheaven for all types of transactions using Fragments.
Today in this post we will see how we can apply animations to Fragments when pushing on to a stack.

This is fairly a long example. I will try to explain with code one by one,
You can click on the download link to get the source code.

Fragment

Fragment

Fragment

Here we start.

At first we will see the layout used in the Fragment.

hello_world.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:text="@string/hello_world"
    android:textAppearance="?android:attr/textAppearanceMedium" />

Now the layout for the activity.
fragment_stack.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="4dip" >

    <FrameLayout
        android:id="@+id/simple_fragment"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </FrameLayout>

    <Button
        android:id="@+id/new_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/new_fragment" >

        <requestFocus />
    </Button>

</LinearLayout>

Now the xml for the animations in the Fragment.
First create a folder inside res folder called “animator” and create four xml files inside it.

fragment_slide_left_enter.xml
fragment_slide_left_exit.xml
fragment_slide_right_enter.xml
fragment_slide_right_exit.xml

fragment_slide_left_enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="100dp" android:valueTo="0dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0.0" android:valueTo="1.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

fragment_slide_left_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0dp" android:valueTo="-100dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="1.0" android:valueTo="0.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

fragment_slide_right_enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="-100dp" android:valueTo="0dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0.0" android:valueTo="1.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

fragment_slide_right_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0dp" android:valueTo="100dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="1.0" android:valueTo="0.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

Now the activity that do all the transactions in the Fragment.

FragmentCustomAnimations.java

package com.example.fragmentcustomanimations;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Demonstrates the use of custom animations in a FragmentTransaction when
 * pushing and popping a stack.
 */
public class FragmentCustomAnimations extends Activity {
    int mStackLevel = 1;

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

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.new_fragment);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                addFragmentToStack();
            }
        });

        if (savedInstanceState == null) {
            // Do first time initialization -- add initial fragment.
            Fragment newFragment = CountingFragment.newInstance(mStackLevel);
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.add(R.id.simple_fragment, newFragment).commit();
        } else {
            mStackLevel = savedInstanceState.getInt("level");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("level", mStackLevel);
    }


    void addFragmentToStack() {
        mStackLevel++;

        // Instantiate a new fragment.
        Fragment newFragment = CountingFragment.newInstance(mStackLevel);

        // Add the fragment to the activity, pushing this transaction
        // on to the back stack.
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
                R.animator.fragment_slide_left_exit,
                R.animator.fragment_slide_right_enter,
                R.animator.fragment_slide_right_exit);
        ft.replace(R.id.simple_fragment, newFragment);
        ft.addToBackStack(null);
        ft.commit();
    }

    public static class CountingFragment extends Fragment {
        int mNum;
        /**
         * Create a new instance of CountingFragment, providing "num"
         * as an argument.
         */
        static CountingFragment newInstance(int num) {
            CountingFragment f = new CountingFragment();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);

            return f;
        }

        /**
         * When creating, retrieve this instance's number from its arguments.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        /**
         * The Fragment's UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.hello_world, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText("Fragment #" + mNum);
            tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));  
            return v;
        }
    }

}

You can download the complete source code from here.

How to create animation by default in a GridLayout in Android?

This example shows you how to create animation using the default XML tag in a gridview.

This application demonstrates how to use the animateLayoutChanges tag in XML to automate
transition animations as items are removed from or added to a container.

Click on the download link to get the source code.

Let’s have a look.

GridLayout Animation

At first we will look at the layout XML.

layout_animations_by_default.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/addNewButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Button" />

    <GridLayout
        android:id="@+id/gridContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"
        android:columnCount="4" />

</LinearLayout>

Now the Activity that uses this XML to create the animation.
LayoutAnimationsByDefault.java

package com.example.animationdemo1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;

/**
 * This application demonstrates how to use the animateLayoutChanges tag in XML to automate
 * transition animations as items are removed from or added to a container.
 */
public class LayoutAnimationsByDefault extends Activity {

    private int numButtons = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_animations_by_default);

        final GridLayout gridContainer = (GridLayout) findViewById(R.id.gridContainer);

        Button addButton = (Button) findViewById(R.id.addNewButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Button newButton = new Button(LayoutAnimationsByDefault.this);
                newButton.setText(String.valueOf(numButtons++));
                newButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        gridContainer.removeView(v);
                    }
                });
                gridContainer.addView(newButton, Math.min(1, gridContainer.getChildCount()));
            }
        });
    }

}

You can download the complete source code for the above post from here.

How to use ImageSwitcher in Android?

You can read more about ImageSwitcher here

http://developer.android.com/reference/android/widget/ImageSwitcher.html

ImageSwitcher1

ImageSwitcher1

Click on the link below to download the code.

This is the layout that contains the ImageSwitcher

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageSwitcher
        android:id="@+id/switcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <Gallery
        android:id="@+id/gallery"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="#55000000"
        android:gravity="center_vertical"
        android:spacing="16dp" />

</RelativeLayout>

What we will do is we will load some images into the Gallery and then load each image into the ImageSwitcher on clicking on each item in the Gallery.
Here is the java class that does it.

package com.example.imageswitcherdemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity implements
		AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_main);

		mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
		mSwitcher.setFactory(this);
		mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));

		Gallery g = (Gallery) findViewById(R.id.gallery);
		g.setAdapter(new ImageAdapter(this));
		g.setOnItemSelectedListener(this);
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		mSwitcher.setImageResource(mImageIds[position]);
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		return i;
	}

	private ImageSwitcher mSwitcher;

	public class ImageAdapter extends BaseAdapter {
		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return mThumbIds.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);

			i.setImageResource(mThumbIds[position]);
			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			i.setBackgroundResource(R.drawable.picture_frame);
			return i;
		}

		private Context mContext;

	}

	private Integer[] mThumbIds = { R.drawable.sample_thumb_0,
			R.drawable.sample_thumb_1, R.drawable.sample_thumb_2,
			R.drawable.sample_thumb_3, R.drawable.sample_thumb_4,
			R.drawable.sample_thumb_5, R.drawable.sample_thumb_6,
			R.drawable.sample_thumb_7 };

	private Integer[] mImageIds = { R.drawable.sample_0, R.drawable.sample_1,
			R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
			R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 };

}

Make sure you have all these resources in the drawable folder

private Integer[] mThumbIds = { R.drawable.sample_thumb_0,
			R.drawable.sample_thumb_1, R.drawable.sample_thumb_2,
			R.drawable.sample_thumb_3, R.drawable.sample_thumb_4,
			R.drawable.sample_thumb_5, R.drawable.sample_thumb_6,
			R.drawable.sample_thumb_7 };

	private Integer[] mImageIds = { R.drawable.sample_0, R.drawable.sample_1,
			R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
			R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 };

You can download the complete java source code from here

ListView Bottom to Top Animation in Android.

Like my previous posts animation chapter is again continued. This time the animation in on a ListView from Bottom to Top.
You have already seen animations from Top to Bottom in my previous posts.
See some of my posts here.

All animation posts from CoderzHeaven is here

Bottom Top animation

Click on the download link at the bottom to download the source code.

So We will start

Like my other examples for this animation also we need two XML files one which extends the “layoutAnimation” class
Here is how it looks
layout_bottom_to_top_slide.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="30%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />

Now the animation for Sliding to right.
slide_right.xml
After applying this animation the View will slide from right side of the screen.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator" >

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromXDelta="-100%p"
        android:toXDelta="0" />

</set>

Our animation XML files are complete.
Now we will apply this in the layout.
activity_main.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

Now just set this layout as the content of your activity. You can see the animation.
Just like this

package com.example.reverseanimationlistviews;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, mStrings));
	}

	private String[] mStrings = { "CoderzHeaven", "Android", "Google", "iPhone",
			"Windows Phone", "Samsung", "Sony" };
}

Note : Changing the delay in the XML, you can change the speed of the animation.

Download the complete Android source code from here.

Creating a Drawable animation in Android.

This is a simple example of how to animate a drawable in Android.
This example is from the official android demo applications.

Animate Drawable

Animate Drawable

Here we have 5 java classes.
AnimateDrawable.java
AnimateDrawables.java
GraphicsActivity.java
PictureLayout.java
ProxyDrawable.java

AnimateDrawable.java

package com.coderzheaven.animatedrawable;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Transformation;

public class AnimateDrawable extends ProxyDrawable {

    private Animation mAnimation;
    private Transformation mTransformation = new Transformation();

    public AnimateDrawable(Drawable target) {
        super(target);
    }

    public AnimateDrawable(Drawable target, Animation animation) {
        super(target);
        mAnimation = animation;
    }

    public Animation getAnimation() {
        return mAnimation;
    }

    public void setAnimation(Animation anim) {
        mAnimation = anim;
    }

    public boolean hasStarted() {
        return mAnimation != null && mAnimation.hasStarted();
    }

    public boolean hasEnded() {
        return mAnimation == null || mAnimation.hasEnded();
    }

    @Override
    public void draw(Canvas canvas) {
        Drawable dr = getProxy();
        if (dr != null) {
            int sc = canvas.save();
            Animation anim = mAnimation;
            if (anim != null) {
                anim.getTransformation(
                                    AnimationUtils.currentAnimationTimeMillis(),
                                    mTransformation);
                canvas.concat(mTransformation.getMatrix());
            }
            dr.draw(canvas);
            canvas.restoreToCount(sc);
        }
    }
}

AnimateDrawables.java


package com.coderzheaven.animatedrawable;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

public class AnimateDrawables extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private AnimateDrawable mDrawable;

        public SampleView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);

            Drawable dr = context.getResources().getDrawable(R.drawable.ic_launcher);
            dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());

            Animation an = new TranslateAnimation(0, 100, 0, 200);
            an.setDuration(2000);
            an.setRepeatCount(-1);
            an.initialize(10, 10, 10, 10);

            mDrawable = new AnimateDrawable(dr, an);
            an.startNow();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);

            mDrawable.draw(canvas);
            invalidate();
        }
    }
}

GraphicsActivity.java

package com.coderzheaven.animatedrawable;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

class GraphicsActivity extends Activity {
    // set to true to test Picture
    private static final boolean TEST_PICTURE = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}

PictureLayout.java


package com.coderzheaven.animatedrawable;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

    public PictureLayout(Context context) {
        super(context);
    }

    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth()/2;
        int y = getHeight()/2;

        drawPict(canvas, 0, 0, x, y,  1,  1);
		drawPict(canvas, x, 0, x, y, -1,  1);
		drawPict(canvas, 0, y, x, y,  1, -1);
		drawPict(canvas, x, y, x, y, -1, -1);
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

ProxyDrawable.java

package com.coderzheaven.animatedrawable;

import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

public class ProxyDrawable extends Drawable {

    private Drawable mProxy;
    private boolean mMutated;

    public ProxyDrawable(Drawable target) {
        mProxy = target;
    }

    public Drawable getProxy() {
        return mProxy;
    }

    public void setProxy(Drawable proxy) {
        if (proxy != this) {
            mProxy = proxy;
        }
    }

    @Override
    public void draw(Canvas canvas) {
        if (mProxy != null) {
            mProxy.draw(canvas);
        }
    }

    @Override
    public int getIntrinsicWidth() {
        return mProxy != null ? mProxy.getIntrinsicWidth() : -1;
    }

    @Override
    public int getIntrinsicHeight() {
        return mProxy != null ? mProxy.getIntrinsicHeight() : -1;
    }

    @Override
    public int getOpacity() {
        return mProxy != null ? mProxy.getOpacity() : PixelFormat.TRANSPARENT;
    }

    @Override
    public void setFilterBitmap(boolean filter) {
        if (mProxy != null) {
            mProxy.setFilterBitmap(filter);
        }
    }

    @Override
    public void setDither(boolean dither) {
        if (mProxy != null) {
            mProxy.setDither(dither);
        }
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        if (mProxy != null) {
            mProxy.setColorFilter(colorFilter);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        if (mProxy != null) {
            mProxy.setAlpha(alpha);
        }
    }

    @Override
    public Drawable mutate() {
        if (mProxy != null && !mMutated && super.mutate() == this) {
            mProxy.mutate();
            mMutated = true;
        }
        return this;
    }
}

Download the complete source code from here

Join the Forum discussion on this post

GridView RandomFade animation in Android

In some of my older posts I have already showed a lot of animations on ListView and GridViews. Search coderzheaven for ListView and GridView animations if you want to see the articles and posts.

This is also yet another post on animation. Here what I will do is create an animation in a GridView such that all cells will appear “RANDOM” with a fade animation.

GridView Random Animation
GridView Random Animation

So we will start

Click on the download link to download the code.

We will start with the animation XML first.

First create a folder named “anim” inside the “res” folder of your project.
Inside it create fade.xml and copy this code into it.

fade.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0"
       android:duration="@android:integer/config_longAnimTime" />

Then create anotther xml file named “layout_random_fade.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="0.5"
        android:animationOrder="random"
        android:animation="@anim/fade" />

This is the factor that creates the random animation.
android:animationOrder=”random”

And this one creates the fade animation.
android:animation=”@anim/fade”

Now we will write the activity that uses the gridview to create the animation.

package com.coderzheaven.gridviewrandomfadeanimation;

import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		loadApps();

		setContentView(R.layout.activity_main);
		GridView grid = (GridView) findViewById(R.id.grid);
		grid.setAdapter(new AppsAdapter());

	}

	private List<ResolveInfo> mApps;

	private void loadApps() {
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

		mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
	}

	public class AppsAdapter extends BaseAdapter {
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(MainActivity.this);

			ResolveInfo info = mApps.get(position % mApps.size());

			i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
			i.setScaleType(ImageView.ScaleType.FIT_CENTER);
			final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f);
			i.setLayoutParams(new GridView.LayoutParams(w, w));
			return i;
		}

		public final int getCount() {
			return Math.min(32, mApps.size());
		}

		public final Object getItem(int position) {
			return mApps.get(position % mApps.size());
		}

		public final long getItemId(int position) {
			return position;
		}
	}
}

Ok Now it’s done. Run the project and see the result.

You can download the complete java android sample code from here.

Cascade animation in a ListView in Android.

Here is a simple example for cascade animation of a listview in android.

ListView cascade

ListView cascade

We use these classes for achieving this.

1. AnimationSet
Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values.

The way that AnimationSet inherits behavior from Animation is important to understand. Some of the Animation attributes applied to AnimationSet affect the AnimationSet itself, some are pushed down to the children, and some are ignored, as follows:

duration, repeatMode, fillBefore, fillAfter: These properties, when set on an AnimationSet object, will be pushed down to all child animations.
repeatCount, fillEnabled: These properties are ignored for AnimationSet.
startOffset, shareInterpolator: These properties apply to the AnimationSet itself.

2. TranslateAnimation

Read about TranslateAnimation classes here.

LayoutAnimationController
A layout animation controller is used to animated a layout’s, or a view group’s, children. Each child uses the same animation but for every one of them, the animation starts at a different time. A layout animation controller is used by ViewGroup to compute the delay by which each child’s animation start must be offset. The delay is computed by using characteristics of each child, like its index in the view group. This standard implementation computes the delay by multiplying a fixed amount of miliseconds by the index of the child in its parent view group. Subclasses are supposed to override getDelayForView(android.view.View) to implement a different way of computing the delay. For instance, a GridLayoutAnimationController will compute the delay based on the column and row indices of the child in its parent view group. Information used to compute the animation delay of each child are stored in an instance of LayoutAnimationController.AnimationParameters, itself stored in the ViewGroup.LayoutParams of the view.

Just copy this simple code to your activity and see the cascading animation in the ListView.

package com.coderzheaven.listcascadeanimation;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mStrings));

        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f); 
        animation.setDuration(500);
        set.addAnimation(animation);

        animation = new TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
        );
        animation.setDuration(100);
        set.addAnimation(animation);

        LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
        ListView listView = getListView();        
        listView.setLayoutAnimation(controller);
    }

    private String[] mStrings = {
        "Bordeaux",
        "Lyon",
        "Marseille",
        "Nancy",
        "Paris",
        "Toulouse",
        "Strasbourg"
    };
}

Different types of Animation – Push Up in, Push Up Out, Push Left in, Push Left Out, HyperSpace In, HyperSpace Out in a ViewFlipper in Android.

Hello all….
This is going to be a big post..

Check out my previous post for a rotate3D animation between a ListView and an Image.

How to create a rotate 3D Animation between a ListView and an ImageView in Android?

Today I will show you different types of Animations using ViewFlipper in a textView.

Here we have 4 TextViews which we will animate one after another using different animations.

I will introduce 4 sample animations which you can modify in any way according to your need.

Animations will be shown in a listview which onclick will animate the ViewFlipper.

At first you have to create a folder named “anim” inside the “res” folder and copy these XML files inside it.

hyperspace_in.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromAlpha="0.0"
    android:startOffset="1200"
    android:toAlpha="1.0" />

hyperspace_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >

    <scale
        android:duration="700"
        android:fillAfter="false"
        android:fillEnabled="true"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.4"
        android:toYScale="0.6" />

    <set android:interpolator="@android:anim/accelerate_interpolator" >
        <scale
            android:duration="400"
            android:fillAfter="true"
            android:fillBefore="false"
            android:fillEnabled="true"
            android:fromXScale="1.4"
            android:fromYScale="0.6"
            android:pivotX="50%"
            android:pivotY="50%"
            android:startOffset="700"
            android:toXScale="0.0"
            android:toYScale="0.0" />

        <rotate
            android:duration="400"
            android:fillAfter="true"
            android:fillBefore="false"
            android:fillEnabled="true"
            android:fromDegrees="0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:startOffset="700"
            android:toDegrees="-45"
            android:toYScale="0.0" />
    </set>

</set>

push_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromXDelta="100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />

</set>

push_left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromXDelta="0"
        android:toXDelta="-100%p" />

    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />

</set>

push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromYDelta="100%p"
        android:toYDelta="0" />

    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />

</set>

push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromYDelta="0"
        android:toYDelta="-100%p" />

    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />

</set>

All animation XML files are over. Now copy this XML to your main layout file.

animation_2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dip" >

    <ViewFlipper
        android:id="@+id/flipper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:flipInterval="2000" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Hello"
            android:textSize="26sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="From"
            android:textSize="26sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="CoderzHeaven"
            android:textSize="26sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Heaven of all working Codes"
            android:textSize="26sp" />
    </ViewFlipper>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:text="Select the Animation to Apply" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

OK Done. Now our Layout files and animation files are over.

Now the MainActivity that uses these animation XML files and layouts.
MainActivity.java

package com.example.pushupanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.ViewFlipper;

public class MainActivity extends Activity implements
		AdapterView.OnItemSelectedListener {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.animation_2);

		mFlipper = ((ViewFlipper) this.findViewById(R.id.flipper));
		mFlipper.startFlipping();

		Spinner s = (Spinner) findViewById(R.id.spinner);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, mStrings);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);
		s.setOnItemSelectedListener(this);
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		switch (position) {

		case 0:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_up_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_up_out));
			break;
		case 1:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_out));
			break;
		case 2:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					android.R.anim.fade_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					android.R.anim.fade_out));
			break;
		default:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.hyperspace_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.hyperspace_out));
			break;
		}
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	private String[] mStrings = { "Push up", "Push left", "Cross fade",
			"Hyperspace" };

	private ViewFlipper mFlipper;

}

Read complete android sample code for this post from here

How to create a rotate 3D Animation between a ListView and an ImageView in Android?

At first we will create a class called “Rotate3dAnimation” which is responsible for the 3D Animation.

The Rotate3dAnimation.java looks like this.

package com.example.transition3d;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

/**
 * An animation that rotates the view on the Y axis between two specified angles.
 * This animation also adds a translation on the Z axis (depth) to improve the effect.
 */
public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    /**
     * Creates a new 3D rotation on the Y axis. The rotation is defined by its
     * start angle and its end angle. Both angles are in degrees. The rotation
     * is performed around a center point on the 2D space, definied by a pair
     * of X and Y coordinates, called centerX and centerY. When the animation
     * starts, a translation on the Z axis (depth) is performed. The length
     * of the translation can be specified, as well as whether the translation
     * should be reversed in time.
     *
     * @param fromDegrees the start angle of the 3D rotation
     * @param toDegrees the end angle of the 3D rotation
     * @param centerX the X center of the 3D rotation
     * @param centerY the Y center of the 3D rotation
     * @param reverse true if the translation should be reversed, false otherwise
     */
    public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

The Matrix class holds a 3×3 matrix for transforming coordinates. Matrix does not have a constructor, so it must be explicitly initialized using either reset() – to construct an identity matrix, or one of the set..() functions (e.g. setTranslate, setRotate, etc.).

Read more about Matrix Classes here.

Now the MainActivity that contains a ListView and an Image.
What we are going to do here is When we click the ListView the ListView will rotate with a 3D Animation and show the Image on the other side.

MainActivity.java

package com.example.transition3d;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends Activity implements
		AdapterView.OnItemClickListener, View.OnClickListener {
	private ListView mPhotosList;
	private ViewGroup mContainer;
	private ImageView mImageView;

	// Names of the photos we show in the list
	private static final String[] PHOTOS_NAMES = new String[] { "Lyon",
			"Livermore", "Tahoe Pier", "Lake Tahoe", "Grand Canyon", "Bodie" };

	// Resource identifiers for the photos we want to display
	private static final int[] PHOTOS_RESOURCES = new int[] {
			R.drawable.photo1, R.drawable.photo2, R.drawable.photo3,
			R.drawable.photo4, R.drawable.photo5, R.drawable.photo6 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.animations_main_screen);

		mPhotosList = (ListView) findViewById(android.R.id.list);
		mImageView = (ImageView) findViewById(R.id.picture);
		mContainer = (ViewGroup) findViewById(R.id.container);

		// Prepare the ListView
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, PHOTOS_NAMES);

		mPhotosList.setAdapter(adapter);
		mPhotosList.setOnItemClickListener(this);

		// Prepare the ImageView
		mImageView.setClickable(true);
		mImageView.setFocusable(true);
		mImageView.setOnClickListener(this);

		// Since we are caching large views, we want to keep their cache
		// between each animation
		mContainer
				.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
	}

	/**
	 * Setup a new 3D rotation on the container view.
	 * 
	 * @param position
	 *            the item that was clicked to show a picture, or -1 to show the
	 *            list
	 * @param start
	 *            the start angle at which the rotation must begin
	 * @param end
	 *            the end angle of the rotation
	 */
	private void applyRotation(int position, float start, float end) {
		// Find the center of the container
		final float centerX = mContainer.getWidth() / 2.0f;
		final float centerY = mContainer.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
				centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(position));

		mContainer.startAnimation(rotation);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		// Pre-load the image then start the animation
		mImageView.setImageResource(PHOTOS_RESOURCES[position]);
		applyRotation(position, 0, 90);
	}

	public void onClick(View v) {
		applyRotation(-1, 180, 90);
	}

	/**
	 * This class listens for the end of the first half of the animation. It
	 * then posts a new action that effectively swaps the views when the
	 * container is rotated 90 degrees and thus invisible.
	 */
	private final class DisplayNextView implements Animation.AnimationListener {
		private final int mPosition;

		private DisplayNextView(int position) {
			mPosition = position;
		}

		public void onAnimationStart(Animation animation) {
		}

		public void onAnimationEnd(Animation animation) {
			mContainer.post(new SwapViews(mPosition));
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}

	/**
	 * This class is responsible for swapping the views and start the second
	 * half of the animation.
	 */
	private final class SwapViews implements Runnable {
		private final int mPosition;

		public SwapViews(int position) {
			mPosition = position;
		}

		public void run() {
			final float centerX = mContainer.getWidth() / 2.0f;
			final float centerY = mContainer.getHeight() / 2.0f;
			Rotate3dAnimation rotation;

			if (mPosition > -1) {
				mPhotosList.setVisibility(View.GONE);
				mImageView.setVisibility(View.VISIBLE);
				mImageView.requestFocus();

				rotation = new Rotate3dAnimation(90, 180, centerX, centerY,
						310.0f, false);
			} else {
				mImageView.setVisibility(View.GONE);
				mPhotosList.setVisibility(View.VISIBLE);
				mPhotosList.requestFocus();

				rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
						310.0f, false);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			mContainer.startAnimation(rotation);
		}
	}

}

Now the layout for the MainActivity.java

animations_main_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@android:id/list"
        android:persistentDrawingCache="animation|scrolling"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

    <ImageView
        android:id="@+id/picture"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

</FrameLayout>

Now we have some XML files for the animation of the ListView when it loads.
Here we are applying a bottom to top slide animation in the ListView when it loads.
So for that you have to first create a folder named “anim” in the “res” folder and create an XML named “layout_bottom_to_top_slide.xml” inside it.

layout_bottom_to_top_slide.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="50%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />

Now you will get an error at this line.

android:animation="@anim/slide_right" 

So for that we create another animation. Create another XML inside the same “anim” folder, but now it is named “slide_right.xml”

slide_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
            android:duration="@android:integer/config_shortAnimTime" />
</set>

This is the translate animation that slides each row in the ListView.

Make sure you have six sample images with the named “photo1.jpg or png” , photo2.jpg etc…

Download the complete Android sample source code from here.

Join the Forum discussion on this post

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to create a blinking text in Android?

Hello everyone…

Here I am explaining two methods on how to create a blinking textview in Android.

One with the help of Animation class and other with a Logic.

Now let’s see that..

Place a textview with an id of “tv” in your layout and attempt this.

package com.coderzheaven.blinktext;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blinkText();
        //blinkText2();
    }
    
    private void blinkText(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
            int timeToBlink = 1000;    //in ms
            try{
            	Thread.sleep(timeToBlink);
        	}catch (Exception e) {
        		
        	}
            handler.post(new Runnable() {
                @Override
                    public void run() {
                    TextView txt = (TextView) findViewById(R.id.tv);
                    if(txt.getVisibility() == View.VISIBLE){
                        txt.setVisibility(View.INVISIBLE);
                    }else{
                        txt.setVisibility(View.VISIBLE);
                    }
                    blinkText();
                }
                });
            }}).start();
   }
    
    public void blinkText2(){
    	TextView myText = (TextView) findViewById(R.id.tv );

    	Animation anim = new AlphaAnimation(0.0f, 1.0f);
    	anim.setDuration(50); //You can manage the time of the blink with this parameter
    	anim.setStartOffset(20);
    	anim.setRepeatMode(Animation.REVERSE);
    	anim.setRepeatCount(Animation.INFINITE);
    	myText.startAnimation(anim);
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    
}

Download the complete android source code from below.

Download.