Thursday, July 24, 2014

Flip ImageView Vertically and Horizontally Use Property Animation

In Android Property animation creates an animation by modifying an object's property values over a set period of time. With property animation we can animate almost any object. You can define duration, interpolation, repeat count, animation set and frame refesh time.
In this post we will animate ImageView to flip vertically and horizontally at the same time each time we tap the screen. ImageView have 3 properties that 2 of them we will use in this project ie. "rotationX" to flip vertically and "rotationY" to flip horizontally.
Now create new project and add these 2 image to drawable-mdpi folder :



In activity_main.xml declare four imageview with id: iview1,iview2,iview3,iview4, set all of them at the same place, in this project is in the center of screen and set visibility 2 of them ie. iview2 and iview4 as gone. We will flip iview1 and iview2 as a couple horizontally and iview3 and iview4 vertically.

In MainActivity.java class inside onCreate inflate xml resources above and set image resource for each of them. We create cuatom methode called flipimage. Inside this methode we will animate imageview using ObjectAnimator. This animator have four parameter that we need to fullfill, first is object, in this project is imageview (visibleimg,invisibleimg,visibleimg1,invisibleimg1) , second is name of object's property as string (rotationX, rotationY), thirth is value of from and fouth are value of to in float. In this ObjectAnimator we can set duration (ms) and set interpolator. Also use AnimationListenerAdapter to listen the end of first image animation to start the second one. Both animation (rotationX and rotationY) run at the same time for both couple imageviews. Override onTouchEvent to run flipimage methode every screen tapped.

This project need android API 11 or above and already tested with emulator.
activity_main.xml
<?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">
    
    <ImageView
        android:id="@+id/iview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <ImageView
        android:id="@+id/iview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone"/>
    <ImageView
        android:id="@+id/iview3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <ImageView
        android:id="@+id/iview4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone"/>
    
</RelativeLayout>
MainActivity.java
package com.example.animation2;

import android.animation.AnimatorListenerAdapter;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;


public class MainActivity extends Activity 
{
    private ImageView iview1,iview2,iview3,iview4;
    private Interpolator accelerator = new AccelerateInterpolator();
    private Interpolator decelerator = new DecelerateInterpolator();
    private ObjectAnimator visinvis,invisvis,visinvis1,invisvis1;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //this 2 image flipped horizontally
        iview1 = (ImageView) findViewById(R.id.iview1);
        iview1.setImageResource(R.drawable.kartukid11);
        iview2 = (ImageView) findViewById(R.id.iview2);
        iview2.setImageResource(R.drawable.kartukid114);
        
      //this 2 image flipped vertically
        iview3 = (ImageView) findViewById(R.id.iview3);
        iview3.setImageResource(R.drawable.kartukid11);
        iview4 = (ImageView) findViewById(R.id.iview4);
        iview4.setImageResource(R.drawable.kartukid114);
        
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) 
    {
        //when tapped run flipimage methode
    	if (event.getAction() == MotionEvent.ACTION_DOWN) {flipimage();}
        return true;
    }
    
    private void flipimage() 
    {
    	//first image box flipped horizontally
    	final ImageView visibleimg,invisibleimg;
    	//switch visibleimg from iview1 to iview2 vice versa
    	if (iview1.getVisibility() == View.GONE) 
        {
            visibleimg = iview2;
            invisibleimg = iview1;
        } 
        else 
        {
            invisibleimg = iview2;
            visibleimg = iview1;
        }
    	//animate property rotationY of imageview (hide)use acceleratorinterpolator
        visinvis = ObjectAnimator.ofFloat(visibleimg,"rotationY", 0f, 90f);
        visinvis.setDuration(500);
        visinvis.setInterpolator(accelerator);
       //animate property rotationY of imageview (show) use deceleratorinterpolator
        invisvis = ObjectAnimator.ofFloat(invisibleimg,"rotationY",-90f, 0f);
        invisvis.setDuration(500);
        invisvis.setInterpolator(decelerator);
        //listen to end of first image animation, make it gone & 
        //start second image animation
    	visinvis.addListener(new AnimatorListenerAdapter() 
        {
            @Override
            public void onAnimationEnd(Animator anim) 
            {
                visibleimg.setVisibility(View.GONE);
                invisvis.start();
                invisibleimg.setVisibility(View.VISIBLE);
            }
        });
    	visinvis.start();
    	
    	//second image box flipped vertically
    	final ImageView visibleimg1,invisibleimg1;
    	//switch visibleimg1 from iview3 to iview4 vice versa
    	if (iview3.getVisibility() == View.GONE) 
        {
            visibleimg1 = iview4;
            invisibleimg1 = iview3;
        } 
        else 
        {
            invisibleimg1 = iview4;
            visibleimg1 = iview3;
        }
    	//animate property rotationX of imageview (hide)use acceleratorinterpolator
    	visinvis1 = ObjectAnimator.ofFloat(visibleimg1, "rotationX", 0f, 90f);
        visinvis1.setDuration(500);
        visinvis1.setInterpolator(accelerator);
        //animate property rotationX of imageview (show)use deceleratorinterpolator
        invisvis1 = ObjectAnimator.ofFloat(invisibleimg1,"rotationX",-90f, 0f);
        invisvis1.setDuration(500);
        invisvis1.setInterpolator(decelerator);
        //listen to end of first image	animation, make it gone 
        //& start second image animation
    	visinvis1.addListener(new AnimatorListenerAdapter() 
        {
            @Override
            public void onAnimationEnd(Animator anim) 
            {
                visibleimg1.setVisibility(View.GONE);
                invisvis1.start();
                invisibleimg1.setVisibility(View.VISIBLE);
            }
        });
    	visinvis1.start();
                
    }
}

Captures of emulator :

Saturday, July 19, 2014

Swap Images of Gridview Childs

This project use same custom gridview like previous post also the images. In this project we will swap or exchange 2 images of gridview childs by click two gridview childs sequencially.

In activity_main.xml, just set one gridview and set attibutes numColumn = 3 because we will make 3x3 gridview and place this gridview on top-center of the screen.In MainActivity.java, inside onCreate inflate gridview from xml. Before set adapter for gridview, make an integer array named grida with length 9, it will be used to fill gridview childs and inisialize the value with image from drawable (use image from previous project) so that all gridview child will display correspondent image. Then set adapter to gridview named ImageAdaper with two argument : Context (this) and integer array (grida). Create a new class called ImageAdapter.java that extent BaseAdapter. This adapter class is similar with Android websites example except that constructor have two parameter rather than one, they are Context and integer array. Also instantiate integer array with length 9 called gride at beginning of class. In MainActivity class, to do swap images between gridview childs when clicked set onItemClickListener to define onItemClick callback methode. In this methode at first click fill data1 with data from child clicked and at second click fill first clicked child with data from second clicked child and then fill second clicked child with data from data1 and then don’t forget to invalidateView to make gridview refresh to display latest data. Additionally to set width of gridview child use DisplayMetrics.withPixels to get screen width and then devided by three. 

This project need android API 8 or above and already tested using emulator.



 Here is the complete codes:

activity_main.xml
<RelativeLayout 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"
    tools:context=".MainActivity" >

    <GridView
        android:id="@+id/gview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="3"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    
</RelativeLayout>
MainActivity.java
package com.example.ndsc;

import android.os.Bundle;
import android.app.Activity;
import android.util.DisplayMetrics;
import import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;


public class MainActivity extends Activity 
{
	private GridView gview;
	public static int gwidth;
	private int ccounter,click1,click2,data1;
	private int[] grida =
	{
		R.drawable.kartukid11,R.drawable.kartukid11,R.drawable.kartukid11,
		R.drawable.kartukid114,R.drawable.kartukid114,R.drawable.kartukid114,
		R.drawable.kartukid119,R.drawable.kartukid119,R.drawable.kartukid119
	};
		
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//this codes to get screen width/height
		DisplayMetrics dmetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dmetrics);
		//gridview column width
		gwidth = dmetrics.widthPixels/3;
		
		gview = (GridView) findViewById(R.id.gview);
		// set custom imageadapter with 2 argument (Context,array int)
		gview.setAdapter(new ImageAdapter(this,grida));
		
		gview.setOnItemClickListener(new OnItemClickListener() 
                {
    	           @Override
    	           public void onItemClick(AdapterView<?> parent, View v,
                                                      int position, long id) 
    	           {
    		  	ccounter+=1;  //click counter
    		  	if(ccounter==1)
	    		 {
	    			 click1=position;
	    			 data1=grida[position];
	    		 }
	    		 else if(ccounter==2)
	    		 {
	    			 click2=position;
	    			 grida[click1]=grida[click2];
	    			 grida[click2] = data1;
                                 //invalidate view to refresh gridview
	    			 gview.invalidateViews();
	    			 
	    			 ccounter=0;
	    		 }
    		    }

                 });
	}
	
}
ImageAdapter.java
package com.example.ndsc;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter 
{
	private Context mcontext;
	private ImageView imageView;
	private int[] gride=new int[9]; //set gridview size 3x3
	private int gwidth = MainActivity.gwidth; //gridview column width
	
	// custom constructor with 2 parameter (Context,array int)
	public ImageAdapter(Context context, int[] gridarray)
	{
		mcontext = context;
		gride=gridarray;
	}
	
	@Override
	public int getCount() 
	{
		return gride.length;
	}

	@Override
	public Object getItem(int arg0) 
        {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0)
        {
		// TODO Auto-generated method stub
		return 0;
	}
		
	public View getView(int position, View convertView, ViewGroup parent) 
	{
	      if (convertView == null) 
	      {  
	         imageView = new ImageView(mcontext);
	         imageView.setLayoutParams(new GridView.LayoutParams(gwidth,gwidth));
	         imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
	         imageView.setPadding(3,3,3,3);
	      } 
	      else {imageView = (ImageView) convertView;}
	      //set foreground image 
	      imageView.setImageResource(gride[position]);
	      
	      return imageView;
	   }

}

Friday, July 18, 2014

Fill and Change Images of Gridview from Outside

Gridview is a viewgroup that displays items in a two-dimensional and scrollable grid. The grid items are automatically inserted to the layout using a adapter. Today we will try to fill or change images to gridview childs from outside imageview. This gridview base on Android sites example codes, we just need little modification on ImageAdapter (see codes). 
Create new android project and then put these 3 images (or use your owns) to drawable-mdpi folder. These images will be set as image resources of 3 imageview. We will fill gridview with these 3 images whichever you choose.
 

 
Lets start with activity_main.xml, in this layout set one gridview and three imageview. In gridview attibutes set numColumn = 3 because we will make 3x3 gridview and place this object on top-center of the screen. Place three imageview below this gridview.
In MainActivity.java, inside onCreate inflate gridview and three imageviews, use above three images as image resources for three imageview. Set onClickListener for all imageview to define onClick callback methode to set data1 with image resource in that clicked imageview. 
Before set adapter for gridview, make an integer array named grida with length 9, it will be used to fill gridview childs and inisialize all value with 0 (zero) means that all gridview child will be empty (no image) at first. Then set adapter to gridview named ImageAdaper with two argument : Context (this) and integer array (grida).Create a new class called ImageAdapter.java that extent BaseAdapter. This adapter class is similar with Android websites example except that constructor have two parameter rather than one, they are Context and integer array. Also instantiate integer array wih length 9 called gride at beginning of class.In MainActivity class, to display images to gridview when clicked set onItemClickListener to define onItemClick callback methode. In this methode fill integer array grida with data1 and to make gridview refresh to display latest data use invalidateView. Additionally to set width of gridview child use DisplayMetrics.withPixels to get screen width and then devided by three.

This project need android API 8 or above and already tested with emulator.

activity_main.xml
<RelativeLayout 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"
    tools:context=".MainActivity" >

    <GridView
        android:id="@+id/gview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="3"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    
    <ImageView
    	android:id="@+id/iview1"
    	android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_below="@id/gview"
        android:layout_alignParentLeft="true" />"
        
    <ImageView
    	android:id="@+id/iview2"
    	android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_below="@id/gview"
        android:layout_alignParentRight="true" />"
        
    <ImageView
    	android:id="@+id/iview3"
    	android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_below="@id/gview"
        android:layout_centerHorizontal="true" />"

</RelativeLayout>
MainActivity.java
package com.example.ndsc;

import android.os.Bundle;
import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity 
{
	private GridView gview;
	public static int gwidth;
	private ImageView iview1,iview2,iview3;
	private int data1;
	private int[] grida ={0,0,0,0,0,0,0,0,0};
		
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//this codes to get screen width/height
		DisplayMetrics dmetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dmetrics);
		//gridview column width
		gwidth = dmetrics.widthPixels/3;
		
		gview = (GridView) findViewById(R.id.gview);
		// set custom imageadapter with 2 argument (Context,array int)
		gview.setAdapter(new ImageAdapter(this,grida));
		
		iview1= (ImageView) findViewById(R.id.iview1);
		iview1.setImageResource(R.drawable.kartukid114);
		iview1.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View view) 
			{
				data1=R.drawable.kartukid114;
			}
			
		});
		iview2= (ImageView) findViewById(R.id.iview2);
		iview2.setImageResource(R.drawable.kartukid119);
		iview2.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View view) 
			{
				data1=R.drawable.kartukid119;
			}
			
		});
		iview3= (ImageView) findViewById(R.id.iview3);
		iview3.setImageResource(R.drawable.kartukid11);
		iview3.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View view) 
			{
				data1=R.drawable.kartukid11;
			}
			
		});
		
		gview.setOnItemClickListener(new OnItemClickListener() 
                {
    	            @Override
    	            public void onItemClick(AdapterView<?> parent, View v,
                                                       int position, long id) 
    	            {
    		  	//fill gridview child with data1
    		  	grida[position]=data1;
                        //invalidate view to refresh gridview
    		  	gview.invalidateViews();
    	            }

                });
	}
	
}
ImageAdapter.java
package com.example.ndsc;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter 
{
	private Context mcontext;
	private ImageView imageView;
	private int[] gride=new int[9]; //set gridview size 3x3
	private int gwidth = MainActivity.gwidth; //gridview column width
	
	// custom constructor with 2 parameter (Context,array int)
	public ImageAdapter(Context context, int[] gridarray)
	{
		mcontext = context;
		gride=gridarray;
	}
	
	@Override
	public int getCount() 
	{
		return gride.length;
	}

	@Override
	public Object getItem(int arg0) 
        {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0)
        {
		// TODO Auto-generated method stub
		return 0;
	}
		
	public View getView(int position, View convertView, ViewGroup parent) 
	{
	      if (convertView == null) 
	      {  
	         imageView = new ImageView(mcontext);
	         imageView.setLayoutParams(new GridView.LayoutParams(gwidth,gwidth));
	         imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
	         imageView.setPadding(3,3,3,3);
	      } 
	      else {imageView = (ImageView) convertView;}
	      //set foreground image 
	      imageView.setImageResource(gride[position]);
	      
	      return imageView;
	   }

}