How to create Christmas Card Gallery using Grid view

November 18th, 2011 by aabhaanjan

Lets develop a Christmas Card Gallery application. We will need to follow these steps :
Step 1: Create a new android project using motodev studios.
Step 2: Choose the name and SDK version for the app. Your AndroidManifest.xml will look
like this :
[xml]










[/xml]

Step 3: Put your app launcher icon image into res/drawable folder.
Step 4: Open your res/layout/main.xml and put following code there :

[xml]


[/xml]

Step 5 : Write your app name into res/value/String.xml

[xml]


Hello World
Christmas Card gallery

[/xml]

Step 6 : write following code in your MainActivity.java file

[xml]
package com.cardGallery;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity
{
//—the images to display—
Integer[] imageIDs = {
R.drawable.card1,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card14,
R.drawable.card15

};

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

GridView gridView = (GridView) findViewById(R.id.cardview);
gridView.setAdapter(new ImageAdapter(this));

gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
“Card” + (position + 1) + ” selected”,
Toast.LENGTH_SHORT).show();
}
});
}

public class ImageAdapter extends BaseAdapter
{
private Context context;

public ImageAdapter(Context c)
{
context = c;
}

//—returns the number of images—
public int getCount() {
return imageIDs.length;
}

//—returns the ID of an item—
public Object getItem(int position) {
return position;
}

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

//—returns an ImageView view—
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
}
[/xml]

Step 7 : Run your application it will look like this.
result

Step 8 : In main menu your app icon will be shown like this :
app_icon

Tags: , , , , , , , , , , , , , ,