Wednesday, December 22, 2010

How to compile Launcher / Calendar or any packages/apps from AOSP in eclipse...!!

How to compile the launcher or any app from packages/apps from eclipse

File->New > Android Project-> Create project from existing workspace ->
-> Point to any of the application in AOSP/packages/apps/AlarmClock (or) Calendar any app.

Now you would be facing many compilation errors for most of the apis.
Currently, You would be working with Android SDK.So it would be linking against android.jar provided from SDK version, in which these apis wont be available.


To make it compile in eclipse, you need to do following steps.



1 - when 'make' is made at root of AOSP, certain jar files will be created in /out directory.

/out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/classes-full-debug.jar

2 - In eclipse, right click your project , select properties -> JAVA Build path ->Libraries tab.
You would have option as 'Add Library' in the side.
Click it. Then select 'User Library'-> 'user libraries'.

then click 'New' and give a name to it.
Then select the newly entered name and select 'Add jars' options in the side. Choose the path of the classes-debug.jar.

3 - Back to Java Build path window. Go to 'Order and export' make the newly added library to be at the top.



Done...!! Now you are ready to compile and debug as well...!!



Note :
'classes-full-debug.jar' file is nothing but collection of .classes files required for compilation. But when you want to run the apk build using this method ( eclipse ) on the emulator, we need the corresponding dex files to be present. DEX files are nothing but dalvik compiled files, which android OS requires for running your application. So you need to push the framework.jar created from compiling 'make' @ root of AOSP to the emulator /system/framework.

go to /out/target/product/generic/system/framework/framework.jar

adb -s emulator-5554 remount
adb -s emulator-5554 push framework.jar /system/framework
adb -s emulator-5554 shell reboot.



For reference eclipse screen shots:











Monday, December 20, 2010

Button press / Button states (images) handling in custom View

In this post, i am going to tell you all how to implement,generate button press events in a custom view.

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

"You can replace the button's background image with a state list drawable. A state list drawable is a drawable resource defined in XML that changes its image based on the current state of the button. Once you've defined a state list drawable in XML, you can apply it to your Button with the android:background attribute."

How do we simulate these states, without the state list drawable resource...:)

1 - First i am taking two buttons, and its corresponding images for different states.

2 - So ultimately we need to draw different button images when pressed on the Button Image and when press is released from it. So we need to change the (int) button_states with either of the above constants on touch events.

final int state_pressed = 1;
final int state_normal = 2;
final int state_enabled = 3;
final int state_disabled = 4;

3 - And in onDraw() method, based on the button_state value we pick up the corresponding bitmap and draw it.

4 - We change the button_state value based on touch events. So we need to override
onTouchEvent() api to receive the button press events.When we get

   
ACTION_DOWN - set button_state = state_pressed
ACTION_MOVE - set button_state = state_pressed // Means user keeps pressing the button.
ACTION_UP - set button_state = state_normal


5 - Since we have more than one buttons on the screen, we need to keep track of each of button positions on the screen with the 'Region' variables.And keep button_state1,button_state2 for the corresponding buttons on the screen.

6 - When the onTouchEvent() is invoked for any press events on the screen, check is the co-ordinates falls in which 'Region' of the button, then change the corresponding button_state values. Call invalidate() on each touch events, which calls the 'onDraw()' wherein based on the button_state we draw diff button images, bringing the user the illusion button is pressed.

Note: Since bitmaps are costly in terms of memory, we shouldnt be keep creating bitmaps for each draw() call for switching the button image. You program will crash.
So we need to 'recycle()' the old bitmap and create a new one and assign to it.




switch(buttonState1)
{
case state_pressed:
button2.recycle();
button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.forward_pressed);
break;
case state_normal:
button2.recycle();
button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.forward_default);
break;
case state_enabled:
button2.recycle();
button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.forward_default);
break;
case state_disabled:
//button2.recycle();
//button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.back_pressed);
break;
}


Here is the full code example what i have tried out.

kept these images in drawable directory,
back_default.png, back_pressed.png, back_disabled.png
forward_default.png, forward_pressed.png.




buttonpress.java
------------------


package com.android.buttonpress;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class buttonpress extends Activity {


public class DisplayView extends View
{
int positionX = 5;
int positionY = 15;
Paint mPaint;
final int state_pressed = 1;
final int state_normal = 2;
final int state_enabled = 3;
final int state_disabled = 4;
int buttonState;
int buttonState1;
Region region;
Region region1;
Rect buttonRect;
Rect buttonRect1;
Bitmap button1;
Bitmap button2;
Context mContext;
DisplayView(Context context)
{
super(context);
mContext = context;
mPaint = new Paint();
mPaint.setTextSize(25);
mPaint.setColor(0xFF0000FF);
mPaint.setTextSize(16);
buttonState1 = state_normal;
buttonState = state_normal;
buttonRect = new Rect(10,30,210,110);
buttonRect1 = new Rect(10,150,210,230);
region = new Region(buttonRect);
region1 = new Region(buttonRect1);
button1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.back_default);
button2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.forward_default);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN: {
if(region.contains((int)event.getX(), (int)event.getY()) == true)
{
buttonState = state_pressed;
}
else if(region1.contains((int)event.getX(), (int)event.getY()) == true ){
buttonState = state_disabled;
buttonState1 = state_pressed;
}
invalidate();
break;
}
case MotionEvent.ACTION_UP: {
if(region.contains((int)event.getX(), (int)event.getY())== true)
{
buttonState = state_normal;
}
else if(region1.contains((int)event.getX(), (int)event.getY()) == true){
buttonState = state_normal;
buttonState1 = state_normal;
}
invalidate();
break;
}
}
return true;
}
@Override
public void onDraw(Canvas canvas)
{

canvas.drawText("Custom button press", positionX, positionY, mPaint);
switch(buttonState)
{
case state_pressed:
button1.recycle();
button1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.back_pressed);
break;
case state_normal:
button1.recycle();
button1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.back_default);
break;
case state_enabled:
button1.recycle();
button1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.back_default);
break;
case state_disabled:
button1.recycle();
button1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.back_disabled);
break;
}
canvas.drawBitmap(button1,null,buttonRect,mPaint);

switch(buttonState1)
{
case state_pressed:
button2.recycle();
button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.forward_pressed);
break;
case state_normal:
button2.recycle();
button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.forward_default);
break;
case state_enabled:
button2.recycle();
button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.forward_default);
break;
case state_disabled:
//button2.recycle();
//button2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.back_pressed);
break;
}
canvas.drawBitmap(button2,null,buttonRect1,mPaint);
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayView view = new DisplayView(this);
setContentView(view);
}
}

Sunday, December 12, 2010

Custom Fade in - Fade out animation in a custom view

I was in a situation to implement a fade in - fade out animations between two pictures
in a custom view.

I have an array of bitmaps passed to my custom view. I need to do animation between the images.

1st Image - Shown first. 2nd Image - is Lying behind it.

Required sequence of image display is like below




1st Image - Fades out
2nd Image - Fades in // Both actions parallely

As soon as 2nd image is seen, bring the 3rd image and draw it behind the 2nd image.

2nd Image - Fades out
3rd Image - Fades In // Both actions parallely.

Considering 4 images are in the array.

4th Image - Fades out
1st Image - Fades In. // So this loop continues with number of images in the array.



Lets see how we can achieve this...!!

1 - First thing to know is, using 'Paint' instance we can set alpha value for the paint. Which means,



if alpha -> 0, then the content drawn using this paint will not be seen at all.
Complete transparency will be provided.

if alpha -> 255, then the content will be shown without transparency. i.e literally means, u cannot see contents if any drawn behind it.

if alpha -> 100, then paritally you can see some content(if any) behind the current content.



Using this setAlpha() api of paint, fade -in & fade -out of two images can be applied simultaneously.

2 - We need to do the animation repeatedly over a peroid of time. So we need either a thread or runnable. Since thread is costly, runnables are preferred. In this case we need two threads.



1 - Perform / Decide, when to change the pictures. ( ex. every 5 sec)
2 - Change the alpha values of foreground / backgroud images to bring the fade out - fade in effect. ( ex. 500 milli seconds each alpha value persists )



3 - We need to create two paints, one for foreground image and another for background image.
i.e Paint mForeGroundPaint;
Paint mBackGroundPaint;

4 - Load the bunch of images you need to shuffle across in a ArrayList.

5 - Have a global picCount variable to keep track of current count of images in the arrayList.

6 - Important stuff to remember. Since we are using runnables, which is different from main UI thread, we need to have a handler to send a message to main thread and call the drawing of foreground / background images. Else you will see a crash.

7 - Once the picCount reaches > ArrayList count, make it to zero and shuffle the foreground / background images accordingly.

8 - This runnables will keep running as long the instance of 'customView' life.So make sure when you want to stop it, remove the Runnable from the Handler.

mHandler.removeCallbacks(mAnimationTask);



fadeinout.java
-----------------

  

package com.android.fadein;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

public class fadeinout extends Activity {

public class customview extends View
{
Paint mPaint;
Paint mForeGroundPaint;
Paint mBackGroundPaint;
Rect rect;
ArrayList attachmentList;
int picCount;
int foregrndalpha = 255;
int backgrndalpha = 0;
Runnable mAnimationTask;
H mHandler = new H();
Bitmap contentBitmap;
Canvas Backgroundcanvas;
Bitmap mAttachmentbackGround;
Bitmap mAttachmentforeGround;

Context mContext;
public customview(Context context)
{
super(context);
mContext = context;
mPaint = new Paint();
mPaint.setTextSize(25);
// set Color- blue
mPaint.setColor(0xFF0000FF);
mPaint.setTextSize(16);
mForeGroundPaint = new Paint();
mBackGroundPaint = new Paint();

attachmentList = new ArrayList();
attachmentList.add(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.bear));
attachmentList.add(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.tiger));
attachmentList.add(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.bird));
attachmentList.add(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.fish));

/* assign the background, foreground images */
picCount = 0;
mAttachmentforeGround = attachmentList.get(picCount);
mAttachmentbackGround = attachmentList.get(picCount+1);

contentBitmap = Bitmap.createBitmap( 300,300, Config.ARGB_8888);
Backgroundcanvas = new Canvas(contentBitmap);

foregrndalpha = 255;
rect = new Rect();
rect.left = 10;
rect.top = 30;
rect.right = 310;
rect.bottom = 330;

populateAttachmentBitmap();
fadeInfadeOutImages();
}

/* Periodically changes the mForeGroundPaint alpha value to bring transparency so that it looks like
* forground image is fading out and background image is fading in
*/

public void fadeInfadeOutImages()
{
mAnimationTask = new Runnable()
{

public void run()
{
if(foregrndalpha > 0 )
{
if (foregrndalpha == 255) { // 155
foregrndalpha -= 100;
backgrndalpha = 100;
} else { //100
foregrndalpha -= 155;
backgrndalpha = 255;
}

mForeGroundPaint.setAlpha(foregrndalpha);
mBackGroundPaint.setAlpha(backgrndalpha);
mHandler.sendEmptyMessage(0);
mHandler.postDelayed(mAnimationTask, 500);
}
else
{
foregrndalpha = 255;
backgrndalpha = 0;
/* Once the alpha reaches zero, its time to change the background, foreground images */
if(++picCount < attachmentList.size())
{
mAttachmentforeGround = mAttachmentbackGround;
mAttachmentbackGround = attachmentList.get(picCount);
}
else
{
picCount = 0;
mAttachmentforeGround = mAttachmentbackGround;
mAttachmentbackGround = attachmentList.get(picCount);
}

mForeGroundPaint.setAlpha(foregrndalpha);
mBackGroundPaint.setAlpha(backgrndalpha);
mHandler.sendEmptyMessage(0);
mHandler.postDelayed(mAnimationTask, 3000);
}

}
};
mHandler.postDelayed(mAnimationTask, 5000);

}

/* All email animation changes to the UI thread must be sent
* via this handler to GridElementView
*/

class H extends Handler
{
public void handleMessage(Message m)
{
if(m.what == 0)
{
System.out.println("Handle message");
populateAttachmentBitmap();
invalidate();

}

}
}

public void populateAttachmentBitmap () {

Backgroundcanvas.drawBitmap(mAttachmentbackGround, null, rect, mBackGroundPaint);
Backgroundcanvas.drawBitmap(mAttachmentforeGround, null, rect, mForeGroundPaint);

}

@Override
public void onDraw(Canvas canvas)
{
canvas.drawText("Welcome to custom fadein - fadeout image animation", 10,20, mPaint);
canvas.drawBitmap(contentBitmap, null,rect, mPaint);
}

}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
customview view = new customview(this);
setContentView(view);
}
}

Monday, December 6, 2010

Custom GridView in a dialog...!!

Everybody's aware that inside a dialog, a custom view can be set.

In this post, i am going to discuss how do we set a custom gridview as the custom view for dialog.

My requirement was to display a grid of options for the user to pick up a categories with a icons shown in a 3x3 matrix. User can choose a one by touching it. And the dialog had a title and at the right end a close button to dismiss the dialog.

I will take through step by steps.

1 - Dialog

onCreateDialog(int id) --> Is the function which will be called by framework,when an activity has implmented and showDialog(int id ) is called on activity's instance.
So we go ahead and implement this onCreateDialog(int id) function.

2 - Layouts

The view can be split into two parts.

- LinearLayout vertical orientation holding two elements.

- RelativeLayout - Title and Exit icons at the right extreme.
- GridView - Display 3x3 icons& text as a view.

CategoryDialog.xml
----------------------



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="3dip" >
<ImageView android:id="@+id/close"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:src="@drawable/exit"
/>
<TextView android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="3dp"
android:textColor="#FFF"
android:textSize="20dip"
android:text="Choose Categories"/>
</RelativeLayout>

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"/>
</LinearLayout>




3 - Creating Dialog

Lets use the AlertDialog and set the categoryDialog.xml layout to its setView() api to show the content. what we are exepecting.

Use inflater to create a view by inflating R.layout.categorydialog



AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.categorydialog,(ViewGroup) findViewById(R.id.layout_root));
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dialog = builder.create();
return dialog;




4- Creating GridView.

View layout = inflater.inflate(R.layout.categorydialog,(ViewGroup) findViewById(R.id.layout_root));
GridView gridview = (GridView)layout.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));

- Get the gridView instance from the inflated layout and set a adapter object to draw its content.

- We need to implement a BaseAdapter and when the adapter instance is set to GridView , GridView queries for how many elements and what are their each view to display in the Grid.

- Each view in the grid is Icon (image) and a text corresponding to the category. So we need to create one more layout xml file to hold these content.

categoryContent.xml
--------------------



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<ImageView android:id="@+id/categoryimage"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"/>
<TextView android:id="@+id/categoryText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="3dp"
android:textColor="#FFF"/>

</LinearLayout>



5 - Create a view inflating this layout xml file and set the LayoutParams for each cell size as 90x90.



convertView = mInflater.inflate(R.layout.categorycontent, null);
convertView.setLayoutParams(new GridView.LayoutParams(90, 90));


Note: Since this a view which will be set in GridView as one element of Grid, the layout params must be of type GridView.LayoutParams. This is very important otherwise, the programs will crash in run-time.




public class ImageAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public ImageAdapter(Context c) {
mInflater = LayoutInflater.from(c);
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { // if it's not recycled,
convertView = mInflater.inflate(R.layout.categorycontent, null);
convertView.setLayoutParams(new GridView.LayoutParams(90, 90));
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.categoryText);
holder.icon = (ImageView )convertView.findViewById(R.id.categoryimage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.icon.setAdjustViewBounds(true);
holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.icon.setPadding(8, 8, 8, 8);
holder.title.setText(categoryContent[position]);
holder.icon.setImageResource(mThumbIds[position]);
return convertView;
}
class ViewHolder {
TextView title;
ImageView icon;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.beer, R.drawable.hotel,R.drawable.shopping,
R.drawable.theatre,R.drawable.train, R.drawable.taxi,
R.drawable.gas, R.drawable.police,R.drawable.hospital
};

}
private String[] categoryContent = {
"Pubs", "Restuarants","shopping",
"theatre","train", "taxi",
"gas", "police","hospital"
};
}





griddialog.java
--------------------

Everybody's aware that inside a dialog, a custom view can be set.

In this post, i am going to discuss how do we set a custom gridview as the custom view for dialog.

My requirement was to display a grid of options for the user to pick up a categories with a icons shown in a 3x3 matrix. User can choose a one by touching it. And the dialog had a title and at the right end a close button to dismiss the dialog.

I will take through step by steps.

1 - Dialog

onCreateDialog(int id) --> Is the function which will be called by framework,when an activity has implmented and showDialog(int id ) is called on activity's instance.
So we go ahead and implement this onCreateDialog(int id) function.

2 - Layouts

The view can be split into two parts.

- LinearLayout vertical orientation holding two elements.

- RelativeLayout - Title and Exit icons at the right extreme.
- GridView - Display 3x3 icons& text as a view.

CategoryDialog.xml
----------------------



package com.android.griddialog;

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

public class griddialog extends Activity {
public final int CATEGORY_ID =0;
private Context mContext;
Dialog dialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getApplicationContext();
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.categories);
button.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
showDialog(CATEGORY_ID);
}
});
}
protected Dialog onCreateDialog(int id) {

switch(id) {

case CATEGORY_ID:

AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.categorydialog,(ViewGroup) findViewById(R.id.layout_root));
GridView gridview = (GridView)layout.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));

gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v,int position, long id) {
Toast.makeText(v.getContext(), "Position is "+position, 3000).show();
}
});

ImageView close = (ImageView) layout.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
dialog.dismiss();
}
});

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public ImageAdapter(Context c) {
mInflater = LayoutInflater.from(c);
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { // if it's not recycled,
convertView = mInflater.inflate(R.layout.categorycontent, null);
convertView.setLayoutParams(new GridView.LayoutParams(90, 90));
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.categoryText);
holder.icon = (ImageView )convertView.findViewById(R.id.categoryimage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.icon.setAdjustViewBounds(true);
holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.icon.setPadding(8, 8, 8, 8);
holder.title.setText(categoryContent[position]);
holder.icon.setImageResource(mThumbIds[position]);
return convertView;
}
class ViewHolder {
TextView title;
ImageView icon;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.beer, R.drawable.hotel,R.drawable.shopping,
R.drawable.theatre,R.drawable.train, R.drawable.taxi,
R.drawable.gas, R.drawable.police,R.drawable.hospital
};

}
private String[] categoryContent = {
"Pubs", "Restuarants","shopping",
"theatre","train", "taxi",
"gas", "police","hospital"
};


}

Friday, December 3, 2010

slide up /down translate

Many would be interested to perform some kindaa of slide up or bottom up animation of images on a button click.

Translate animation can be used to perform this.
public TranslateAnimation (float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)

FromX - 0
ToX - 0
FromY - 100
ToY - 0

// This means from the height of 100px, the animation will move up the view upwards untill toY becomes 0. THis looks like the view is moved from bottom up or slide up

What i tried out here

1 - A Linearlayout of height 100px is created and set a edit text inside it.
Intially edit text is set to invisible state.So that first time, application
started you will see nothing.
2 - On the onlick() of Button object
- created a translate animation with fromY = 100
- Set the fillafter(true) so that when animation ends, the position of view will be retained. else the view will not be visible.

3 - start the animation on the edit text object.



public void onClick(View v) {
edit.setVisibility(View.VISIBLE);
TranslateAnimation slide = new TranslateAnimation(0, 0, 100,0 );
slide.setDuration(1000);
slide.setFillAfter(true);
edit.startAnimation(slide);
}
});






edittext.java
----------------



package com.android.edittext;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;

public class edittext extends Activity {
Button b;
EditText edit;
View layout;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit = (EditText)findViewById(R.id.edittext);
b = (Button)findViewById(R.id.button);
layout = (View) findViewById(R.id.layout);
b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
edit.setVisibility(View.VISIBLE);
TranslateAnimation slide = new TranslateAnimation(0, 0, 100,0 );
slide.setDuration(1000);
slide.setFillAfter(true);
edit.startAnimation(slide);
}
});
}
}





layout.xml
------------


<?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"
/>
<Button
android:id="@+id/button"

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="slideup"
/>

<LinearLayout
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="100px"
>

<EditText
android:id="@+id/edittext"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollHorizontally="true"
/>

</LinearLayout>

</LinearLayout>