How to Flip Sprite in Cocos2D ?

Hi,

On certain occasions you may need to flip the sprite you are using in your application.
There are two ways to flip a sprite. Let’s see how this can be done along X-direction
Method:1

mySprite.flipX = 180;

where mySprite is the name of your sprite you want to flip.

Method:2

CCFlipX *flipOnX = [CCFlipX actionWithFlipX:YES];
[mySprite runAction:flipOnX ];

where mySprite is the name of your sprite & flipOnX is the name of the CCFlipX action.

:) . You can try the Y-direction your own!

How to stop the sprite sheet animation in cocos2D ?

Hi,

In one of our previous post we have discussed how to animate sprite sheet in cocos2D.
In some cases you may need to stop the sprite sheet animation abruptly. How to do that?
Here the way to do that. Use the following.

[spriteName stopAction:spriteNameAction];

where spriteName is the name of your sprite & spriteNameAction is the name of your sprite sheet animation action.
:)

Getting name of selected item from NSPopUpButton in Cocoa Mac

Hi,

On many occasions you may need to use a popup button & in cocoa mac you can use NSPopUpButton objects for the same.
While using a pop up button we need to identify the name of the item selected from the pop up list. But how is that done?
You can use the following code for do the same.

NSPopUpButtonCell *nameHere = [sender selectedCell];

nameHere contains the name of your selected item from the NSPopUpButton.
:)

How to create OptionsMenu in ANDROID?, a simple example……

This is a simple example of creating options Menu in ANDROID.
This menu can be seen by clicking on the “Menu Button” in ANDROID.
Check out this example.

	package com.options;

	import android.app.Activity;
	import android.os.Bundle;
	import android.view.Menu;
	import android.view.MenuItem;
	import android.widget.TextView;

	public class myMenu extends Activity {
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	    }

	public boolean onCreateOptionsMenu(Menu menu) {
	  super.onCreateOptionsMenu(menu);
	  menu.add(0,0,0,"My Menu One");
	  menu.add(0,1,0,"My Menu two");
	  menu.add(0,2,0,"My Menu three");
	  menu.add(0,3,0,"My Menu Four");
	  menu.add(0,4,0,"My Menu Five");
	  return true;
	 }

	 public boolean onOptionsItemSelected(MenuItem item) {
	  super.onOptionsItemSelected(item);
	  TextView view = (TextView) findViewById(R.id.tv);
	  switch (item.getItemId()) {
	  case 0:
	      view.setText("Menu selected =>  "+item.getTitle());
	      break;
	  case 1:
		  view.setText("Menu selected => "+item.getTitle());
		  break;
	  case 2:
		  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 3:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 4:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 5:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 6:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  default:
	          view.setText("Nothing found.");
	  break;
	  }
	  return false;
	 }

	 public boolean onPrepareOptionsMenu(Menu menu) {
	  return super.onPrepareOptionsMenu(menu);
	 }
	}

The main.xml for the above code is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:id="@+id/tv"
    />
</LinearLayout>
Options Menu in ANDROID

Options Menu in ANDROID

Context menu in android

What is context menu?
Where it is used?
How it is used?

I will cover all these questions…

Context Menu

A context menu is conceptually similar to the menu displayed when the user performs a “right-click” on a PC. You should use a context menu to provide the user access to actions that pertain to a specific item in the user interface. On Android, a context menu is displayed when the user performs a “long press” (press and hold) on an item.

By two ways we can enable Context menu from listView

First Create an xml to hold the ListView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
 	<ListView android:id="@+id/listview"
		 android:scrollbars="vertical"
	 	 android:layout_width="fill_parent"
	 	 android:layout_height="fill_parent"
	 	 android:layout_gravity="fill_vertical"
	  	 android:layout_alignParentTop="true" >
	</ListView>
</RelativeLayout>

Now its time to create a simple listview in java.
Create a listView and set up a itemClicklistener

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Listview extends Activity {
	 ListView list;
	    private List List_file;
	    public void onCreate(Bundle savedInstanceState)
	    {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        List_file =new ArrayList();
	        list = (ListView)findViewById(R.id.listview);
	 
	        CreateListView();
	    }
	    private void CreateListView()
	    {
	         List_file.add("bird");
	         List_file.add("cat");
	         List_file.add("dog");
	         List_file.add("tiger");
	         List_file.add("goat");
	         //Create an adapter for the listView and add the ArrayList to the adapter.
	         list.setAdapter(new ArrayAdapter(Listview.this, android.R.layout.simple_list_item_1,List_file));
	        // registerForContextMenu(list);
	 
	         list.setOnItemClickListener(new OnItemClickListener()
	         {
	                public void onItemClick(AdapterView arg0, View arg1,
	                        int arg2, long arg3)
	                {
	                }
	        });
	        
	    
	    list.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
	    {
	       public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
	       {
	           // TODO Auto-generated method stub
	            menu.setHeaderTitle("ContextMenu");
	            for (int i = 0; i < 5; i++)
	            {
	                menu.add(0, 0,0, "favorite"+i);
	            }
	       }
	   });
	}
}

The ContextMenu will appear when we long pres the listItem. We can enable this by two method

First Method

 list.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
 {
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
	{
		// TODO Auto-generated method stub
		 menu.setHeaderTitle("ContextMenu");
		 for (int i = 0; i&lt;5; i++)
		 {
			 menu.add(0, 0,0, "favorite"+i);
		 }
	}
});

Second Method
Instead of setting up a listener we can register contextMenu from listView by

registerForContextMenu(list);

Then when the user selects an item from the context menu, the system calls onContextItemSelected(). Here is an example of how you can handle selected items

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
{
		menu.setHeaderTitle("ContextMenu");
	    for (int i = 0; i&lt;5; i++)
	    {
	    	 menu.add(0, 0,0, "favorite"+i);
	    }
}

Blog title not shown in WordPress.

This is one of the common problems found in the site hosted on wordpress.
If your blog title is not showing the title,

Then go to Settings-> General-> Blog title and set the blog title there.

If still the title is not coming..then you must have installed “All in One SEO” as plugin in your wordpress site or blog.
“All in One SEO” overrides the blog title. So what you have to do is go to Settings -> All in One SEO and set the blog title there.
This will solve your problem.
Good luck.

Crop an Image in ANDROID.

Cropping an image in ANDROID programmatically has always been a problem for ANDROID developers.
So Here I am putting a sample code to demonstrate this.
For cropping an image in ANDROID we need a source bitmap which is our image itself, the other one is the target bitmap which we have to
set the size as we want and a matrix.

Below code is a fully working code, just copy and paste this code to your new project.
The XML for the code is also provided below.

Make sure that you have an image named “image.png” in your resources.
Assuming the image to be of size 300×300 pixels.


package Move3.pack;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;

@SuppressWarnings({ "deprecation", "unused" })
public class Move extends Activity {

	public FrameLayout board;
	public View part1;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		 board = new FrameLayout(this);
		 board = (FrameLayout)findViewById(R.id.Board);
		 part1 = new View(this);
		 part1 = findViewById(R.id.part1);
	    try{

	    	Paint paint = new Paint();
			paint.setFilterBitmap(true);
			Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.image);

	        int targetWidth  = 300;
	        int targetHeight = 300;


	        Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,Bitmap.Config.ARGB_8888);

	        RectF rectf = new RectF(0, 0, 100, 100);

	        Canvas canvas = new Canvas(targetBitmap);
	        Path path = new Path();

	        path.addRect(rectf, Path.Direction.CW);
	        canvas.clipPath(path);

	        canvas.drawBitmap( bitmapOrg, new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight()),
	       		 			new Rect(0, 0, targetWidth, targetHeight), paint);



	        Matrix matrix = new Matrix();
	        matrix.postScale(1f, 1f);
	        Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap, 0, 0, 100, 100, matrix, true);

	        /*convert Bitmap to resource */
	        BitmapDrawable bd = new BitmapDrawable(resizedBitmap);

	        part1.setBackgroundDrawable(bd);

        }
    	catch(Exception e){
    		System.out.println("Error1 : " + e.getMessage() + e.toString());
      }

	}

main.xml

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

<View
		android:layout_height="100dp"
		android:layout_width="100dp"
		android:id="@+id/part1"

		>
</FrameLayout>

crop image in android Example

cropping image in android


If you got any errors please let me know.

Sprite Sheet Animation in Cocos2D – An Example

Hi,

Suppose you have a sprite sheet of the desired animation you want. But how will you use that sprite sheet animation in your program using cocos2D? That’s simple. See the following code first.


//Initializing a CCSpriteBatchNode with our sprite sheet image
CCSpriteBatchNode *newSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"jumpingOver.png"];

//Adding the spriteSheet to the layer & setting the z orientations
[self addChild:spriteSheet z:14];

//Creating Frames from the frames file jumpingOver.plist
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"jumpingOver.plist"];

//Initializing a sprite with the first frame from plist
CCSprite *jumper = [CCSprite spriteWithSpriteFrameName:@"jump1.png"];

//Creating an NSMutableArray for adding the frames from plist
NSMutableArray *framesArray = [[NSMutableArray array] retain];

//Iterating for the total number of frames from plist
//Here supposing our jumpingOver plist have 15 images
for(int i=0; i<15; i++){
//Adding frames to our framesArray from the frames
[turningFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"jump%d.png",i]]];
}

//Creating an animation using the frames in framesArray
CCAnimation *jumping = [CCAnimation animationWithFrames:framesArray delay:0.25f];

//Setting our jumper sprite sprite sheet animation to the position of one another sprite
//oldSprite is our previous sprite on that position we are adding the animation
jumper.position=oldSprite.position;

//Creating action from the animation jumping
CCAction *jumpAction= [CCAnimate actionWithAnimation:jumping];

//running the action on jumper sprite with the sprite sheet animation action on jumpAction
[jumper runAction:jumpAction];

//Adding the jumper sprite to the layer with z orientation
[self addChild:jumper z:15];

:)

Adding Image to a UIImageView using Image URL

Hi,

Sometimes you need to add Image to a UIImageView from the URL of the image you got. In that case, this is how you can add image to the UIImageView.

NSString *picURL= @"http://photobucket.com/yourImage.gif";
NSData *picData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mapURL]];
UIImage* picture = [[UIImage alloc] initWithData:picData];
[pictureView setImage:picture];
[picData release];
[picture release];

Here, pictureView is your UIImageView.
:)

How to create a new Virtual SD card in emulator in ANDROID? How to start emulator with the created SDCard?

OK

The first question is
1. How to create a new Virtual SD card in emulator in ANDROID?

Many times we may have not enough memory for our application to run on the emulator.
So what we do?
One method is to create new virtual device with more memory.
Another method is to extend the device’s internal memory.
Third method is to create an SD card for the emulator.

Here is how you create a new SD card for the emulator.
First you have to navigate to you android installation directory and go to tools from there execute this command

C:androidtools>mksdcard -l mySdCard 1024M mySdCardFile.img

A file image named “mySdCardFile” will be created with about 1024 MB memory or you can give it in KB also.

Now SDCard created.Check your C:androidtools directory and confirm that the image has been created.

SDcard

SDcard created

2. How to start emulator with the created SDCard?

Try this in the command prompt
Note: Make sure your emulator(Here VD1.6 created by me) is not running.

C:androidtools>emulator -avd VD1.6 -sdcard mySdCardFile.img

Now go to Eclipse Open DDMS on the right top of the window and open the File-Explorer from the Window-Menu

There you will see the SDcard

No image

SDcard in ANDROID

If you are not starting the emulator with the sdcard you will not see the sdcard here.

You can find more options on emulator here
http://developer.android.com/guide/developing/tools/emulator.html

How to create a scrolling ListView in android?

ListView is like a tableView in iPhone or iOS . In this example i will show you how to add a String Array in to the ListView and also make the listView Scrollable.

First the xml file . Here the line

android:scrollbars=”vertical”

will make the scrolling vertically

<?xml version="1.0" encoding="utf-8"?>
<relativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
	<listView
			android:id="@+id/listview"
			android:scrollbars="vertical"
			android:layout_width="fill_parent"
			android:layout_height="200dip"
			android:layout_gravity="fill_vertical"
			android:layout_alignParentTop="true"
			>
		</listView>

</relativeLayout>

Now the java file

package com.Ch.Example.pack;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Example extends Activity
{
    /** Called when the activity is first created. */
	ListView list;
	private List<string> List_file;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List_file =new ArrayList<string>();
        list = (ListView)findViewById(R.id.listview);

        CreateListView();
    }
	private void CreateListView()
	{
		 List_file.add("Coderzheaven");
		 List_file.add("Google");
		 List_file.add("Android");
		 List_file.add("iPhone");
		 List_file.add("Apple");
		 //Create an adapter for the listView and add the ArrayList to the adapter.
		 list.setAdapter(new ArrayAdapter<string>(Example.this, android.R.layout.simple_list_item_1,List_file));
		 list.setOnItemClickListener(new OnItemClickListener()
		   {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
				{
					//args2 is the listViews Selected index
				}
		   });
	}
}

The screen will be like this

Here is a other useful posts related to listviews.

1. ListView with Sections in android.
2. A Simple Layout with two listViews.

How to read a folder in the assets directory and read files from it in android?

File reading is important in android. For the put the files in the assets folder.

We can able to read

  • foldername
  • filename
  • Contents of the file

First we read the name of the folder.

private String folder_array[];
AssetManager mngr_spinner = getAssets();
try
{
         //"air" is the name of the folder...
	folder_array= mngr_spinner.list("air");
}
catch (IOException e1)
{
	e1.printStackTrace();
}

“folder_array” contains all the names of the folder
Then if the path is set to

folder_array= mngr_spinner.list("air/Buttons Events");

Then the list of file name is got.
If you want to read the file content then do the following..

InputStream is;
try
{
	is = getAssets().open(air/Buttons Events/filename);
	int siz = is.available();
	byte[] buffer = new byte[siz];
	is.read(buffer);
        //This text contains the content of the file..
	String text = new String(buffer);
        is.close();
}
catch (Exception e)
{
	 Toast.makeText(CheatSheet.this,"File Not Found Error.Please ensure that file is not deleted.", Toast.LENGTH_SHORT).show();
}

How to prevent collision between connected bodies in Box2D ?

Hi,

While using Box2D , in many cases you may need to connect two bodies together. But the collision between them during motion is not what you preferred! So how can you prevent those bodies being connected in Box2D from collision?
Use the line of code to prevent the collision.

jointDef.collideConnected = false;

Copying a Sprite Image to another Sprite in Cocos2D

Hi,

Suppose you want to copy a sprite image to another new sprite while using cocos2D. What you do?
See the following code…

Let oldSprite be your first sprite

CCSprite *oldSprite = [CCSprite spriteWithFile:@"ImgOne.png"];

And newSprite be your second sprite

CCSprite *newSprite  = [CCSprite spriteWithTexture:[oldSprite texture]];

That’s it! Done! Now newSprite too contain ImgOne as Sprite.

:)

Playing sound on the Mac Desktop in Objective C.

There are different ways for playing sound on the Mac in Objective C.

Let’s look at some of the methods..
1. Play by filename.

           NSSound *mySound = [NSSound soundNamed:@"sound"];

if you have no file named “sound” in your application’s main bundle, then it will return nil.

2. Play by pathName

           sound = [[NSSound alloc] initWithContentsOfFile:@"/Volumes/Audio/sound.aiff"
           byReference:YES];

3. Play by URL

        NSURL *soundURL = [NSURL
        fileURLWithString:@"file://~/soundfiles/sound.aiff"];
        NSSound *sound = [[NSSound alloc] initWithContentsOfURL:soundURL

byReference:NO];
Then to play the sound add

         if (![sound isPlaying])
                [sound play];

To pause the sound

               [sound pause];

To stop the sound.

              [sound stop];

To resume the sound

             [sound resume];

Please leave your valuable comments if this post was useful…..

Delete a substring in Objective C, Iphone , Mac………….

This code snippet deletes a substring from a original string..

/** initialize two strings **/
NSString *string = @"This is heaven";
NSString *part = @"heaven";

/** Get the range of the substring in the original string **/
NSRange range = [string rangeOfString:part];

/** Delete the substring from the original string **/
[string deleteCharactersInRange:range];

Please leave your valuable comments………

ToolTip Sound in Adobe AIR/FLEX…

Sometimes we may need to have a sound when we hover over something, i.e when a tooltip appears.
Actually this can be done easily by adding an eventListener to the corresponding control.
Take a look at the example.
This line is the important line.

      myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);

The function myListener gets called when we hover over the label thus producing the sound.
What you have to do is to just copy and paste the following code to your file.

       import mx.events.ToolTipEvent;
     import flash.media.Sound;

     [Embed(source="msgAlert.mp3")]

     private var myToolTipSound:Class;
     private var mySound:Sound;

     private function init():void {
        myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);
        mySound = new myToolTipSound();
     }
      public function playSound():void {
        mySound.play();
     }
     private function myListener(event:ToolTipEvent):void {
        playSound();
     }
  ]]>
   

Encapsulation Using Properties in C#.NET / ASP.NET

Hi,

Let’s see how encapsulation can be implemented using properties in C#.NET/ASP.NET.
Let’s see the code first.

using System;

public class Student
{
    private int stud_id = -1;

    public int ID
    {
        get
        {
            return stud_id;
        }
        set
        {
            stud_id = value;
        }
    }

    private string stud_name = string.Empty;

    public string Name
    {
        get
        {
            return stud_name;
        }
        set
        {
            stud_name = value;
        }
    }
}

public class StudentManagerWithProperties
{
    public static void Main()
    {
        Student studObj = new Student();

        studObj.ID = 7;
        studObj.Name = "Aamir Khan";

	Console.WriteLine(
            "ID: {0}, Name: {1}",
            studObj.ID,
            studObj .Name);

        Console.ReadKey();
    }
}

Ok. Here Student class has two properties ID & NAME. Also two private variables or fields stud_name & stud_id, both are encapsulated by our ID & NAME properties. And also two accessors for setting and getting values from fields. Set accessor set the value to the field. Note that the ‘value’ used here is the keyword! This value is assigned by calling function. StudentManagerWithProperties uses the ID & NAME properties as we can see.

:)

AlertView with textbox in iPhone, Objective C.

Often we see alerts with text message or title in it.
But actually we can customize alerts. We can place any views inside it.
We can place a textView(TextField) , imageView etc in it.
Take a look at this simple example that places a textbox inside an alertView.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title goes here!!"
                            message:@"My Message"
                            delegate:self cancelButtonTitle:
                            @"Cancel" otherButtonTitles:@"OK", nil];
UITextField *TF = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[TF setBackgroundColor:[UIColor ClearColor]];
[alert addSubview:TF];        /** adding the textfield to the alertView **/
[alert show];
[alert  release];

Please leave your valuable comments…..

Using GridView in ANDROID….

GridViews are those in which you can arrange elements in a two dimensional grid.
It is what you see in the gallery where images are arranged. Here images are arranged in a two dimensional grid.
Copy the below code and save it as “MyGridView.java”

package com.pack;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MyGridView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this));
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(MyGridView.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}

/********************************* End of MyGridView.java ****************************** **/

Now create another file named “Images.java” and copy the below code to it.

package com.pack;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
lass="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">import android.widget.ImageView;
public class Images extends BaseAdapter {
private Context ctxt;
public Images (Context c) {
ctxt = c;
}
public int getCount() {
return Ids.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int pos) {
return 0;
}
public View getView(int pos, View convertView, ViewGroup parent) {
ImageView imgView;
if (convertView == null) {
imgView = new ImageView(mContext);
imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
} else {
imgView = (ImageView) convertView;
}
imgView.setImageResource(Ids[pos]);
return imgView;
}
private Integer[] Ids = {
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7
};
}
/*********************************** End of Images.java**************************** **/

Note: Please make sure that you have images named img_0 to img_7 in your res/drawable folder.
Please leave your valuable comments if this post was useful…..

Android TableLayout

In android there are different layouts and we often confuse about which one to use. Even if we select one, it is little complicated.

So this tutorials is to show you about the TableLayout

Here i first created linear Layout in which a Table Layout is added

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TableLayout
		android:layout_width="wrap_content"
		android:id="@+id/table"
		android:layout_height="wrap_content">
	<TableRow>
		<EditText
			 android:text=""
			 android:id="@+id/name"
			 android:layout_column="0"
			 android:hint="name"
			 android:layout_width="wrap_content"
			 android:layout_height="wrap_content"
			 android:fadingEdge="vertical|horizontal"/>
	</TableRow>
	<TableRow>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Save"
			android:layout_column="0"
			android:id="@+id/OkButton"
			android:fadingEdge="horizontal">
		</Button>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Cancel"
			android:layout_column="1"
			android:id="@+id/cancelButton"
			android:fadingEdge="horizontal">
		</Button>
	</TableRow>

	</TableLayout>
</LinearLayout>

Here you can see that the first row ie, the EditText length is limited to 1 column and so it is not looking good. So we can make the EditText span across two column by adding this line to EditText

android:layout_span="2"

Now we can position the TableLayout in the center of the screen by adding this to TableLayout

android:layout_gravity = "center_vertical"

Now we think of aligning this to center horizontal as

android:layout_gravity = "center_horizontal"

But this wont work. This is because of LinearLayout and here the positioning is restricted.
But their is solution “Relative Layout” and positioning is easy by using this layout.

I will cover this in my next Post

Alert Button with Image in Adobe AIR/FLEX…

We usually see only alerts with text only, but in Adobe AIR and FLEX we can have alerts with our images in it. That’s really cool right.
Take a look at this simple example. It places an image in the alert.
Make sure that you have the image named “alert_image.png” in your “src” folder or otherwise give the specific path.



 
        
        


No Image

How to Disable Right Click on HTML page using jQuery ?

Hi,

In some special cases you may need to disable the Right Click option on HTML page you are using.
An easy way to do it using jQuery is follows. Use the following code in the HTML page where you want to disable Right Click.

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

:)