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;
	   }

}

No comments:

Post a Comment