19 Oct 2013

External Font Across the Android Application

Hello Friends, Today i am going to share Custom Font style of text view for whole application.

Sometimes in Android app we may need to maintain same font across application. At point of time previews post is not sufficient.

Here below Example shows how to use External font across the application.

Here First I have downloaded ".ttf” file from google. Created a new folder “font” in assets folder and paste your recently downloaded font file.




we can do that by just extending your class from android TextView.

Below code is to my customized TextView class(CustomFontTextView.java)

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomFontTextView extends TextView
{
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle)
 {
  super(context, attrs, defStyle);
  setFont();
 }

 public CustomFontTextView(Context context, AttributeSet attrs)
 {
  // call the constructor which has the complete definition
  this(context, attrs, 0);
 }

 public CustomFontTextView(Context context)
 {
  super(context);
 }

 public void setFont()
 {
  String ttf_fontPath = "fonts/TIMES_SQ.TTF";
Typeface font = Typeface.createFromAsset(getContext().getAssets(),ttf_fontPath);
  setTypeface(font);
 }
}

In our Layout insted of declare <TextView/> tag we just specify <com.hb.CustomFontTextView/>
in any were in our application.

 <com.hb.CustomFontTextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Hello Android"
        android:textColor="#65E561"
        android:textSize="45dp" />

Then external font will be applied to Text.



I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

26 Aug 2013

Unzipping Files with Android (Programmatically) | Extract zip file in android

This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.

The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:

ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class:
-read a zip via its constructor ZipInputStream(FileInputStream)
-read entries of files and directories via method getNextEntry()
-read binary data of current entry via method read(byte)
-close current entry via method closeEntry()
-close the zip file via method close()

ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form:
folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext

Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file.

Below class is used for unzip download zip and extract file and store your desire location.

import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipUtil
{
 private String zipFile;
 private String location;

 public UnzipUtil(String zipFile, String location)
 {
  this.zipFile = zipFile;
  this.location = location;

  dirChecker("");
 }

 public void unzip()
 {
  try
  {
   FileInputStream fin = new FileInputStream(zipFile);
   ZipInputStream zin = new ZipInputStream(fin);
   ZipEntry ze = null;
   while ((ze = zin.getNextEntry()) != null)
   {
    Log.v("Decompress", "Unzipping " + ze.getName());

    if(ze.isDirectory())
    {
     dirChecker(ze.getName());
    }
    else
    {
     FileOutputStream fout = new FileOutputStream(location + ze.getName());     

     byte[] buffer = new byte[8192];
     int len;
     while ((len = zin.read(buffer)) != -1)
     {
      fout.write(buffer, 0, len);
     }
     fout.close();

     zin.closeEntry();

    }

   }
   zin.close();
  }
  catch(Exception e)
  {
   Log.e("Decompress", "unzip", e);
  }

 }

 private void dirChecker(String dir)
 {
  File f = new File(location + dir);
  if(!f.isDirectory())
  {
   f.mkdirs();
  }
 }
}

MainActivity.Class:


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{
 private ProgressDialog mProgressDialog;

 String Url="http://hasmukh/hb.zip";
 String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipFolder/";
 String StorezipFileLocation =Environment.getExternalStorageDirectory() + "/DownloadedZip"; 
 String DirectoryName=Environment.getExternalStorageDirectory() + "/unzipFolder/files/";

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

  DownloadZipfile mew = new DownloadZipfile();
  mew.execute(url);

 }
}

//-This is method is used for Download Zip file from server and store in Desire location.
class DownloadZipfile extends AsyncTask<String, String, String>
{
 String result ="";
 @Override
 protected void onPreExecute()
 {
  super.onPreExecute();
  mProgressDialog = new ProgressDialog(MainActivity.this);
  mProgressDialog.setMessage("Downloading...");
  mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  mProgressDialog.setCancelable(false);
  mProgressDialog.show();
 }

 @Override
 protected String doInBackground(String... aurl)
 {
  int count;

  try
  {
   URL url = new URL(aurl[0]);
   URLConnection conexion = url.openConnection();
   conexion.connect();
   int lenghtOfFile = conexion.getContentLength();
   InputStream input = new BufferedInputStream(url.openStream());

   OutputStream output = new FileOutputStream(StorezipFileLocation);

   byte data[] = new byte[1024];
   long total = 0;

   while ((count = input.read(data)) != -1)
   {
    total += count;
    publishProgress(""+(int)((total*100)/lenghtOfFile));
    output.write(data, 0, count);
   }
   output.close();
   input.close();
   result = "true";

  } catch (Exception e) {

   result = "false";
  }
  return null;

 }
 protected void onProgressUpdate(String... progress)
 {
  Log.d("ANDRO_ASYNC",progress[0]);
  mProgressDialog.setProgress(Integer.parseInt(progress[0]));
 }

 @Override
 protected void onPostExecute(String unused)
 {
  mProgressDialog.dismiss();
  if(result.equalsIgnoreCase("true"))
  {
   try
   {
    unzip();
   } catch (IOException e)
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  else
  {

  }
 }
}
//This is the method for unzip file which is store your location. And unzip folder will store as per your desire location.

public void unzip() throws IOException 
{
 mProgressDialog = new ProgressDialog(MainActivity.this);
 mProgressDialog.setMessage("Please Wait...");
 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
 mProgressDialog.setCancelable(false);
 mProgressDialog.show();
 new UnZipTask().execute(StorezipFileLocation, DirectoryName);
}


private class UnZipTask extends AsyncTask<String, Void, Boolean> 
{
 @SuppressWarnings("rawtypes")
 @Override
 protected Boolean doInBackground(String... params) 
 {
  String filePath = params[0];
  String destinationPath = params[1];

  File archive = new File(filePath);
  try 
  {
   ZipFile zipfile = new ZipFile(archive);
   for (Enumeration e = zipfile.entries(); e.hasMoreElements();) 
   {
    ZipEntry entry = (ZipEntry) e.nextElement();
    unzipEntry(zipfile, entry, destinationPath);
   }


   UnzipUtil d = new UnzipUtil(StorezipFileLocation, DirectoryName); 
   d.unzip();

  } 
  catch (Exception e) 
  {
   return false;
  }

  return true;
 }

 @Override
 protected void onPostExecute(Boolean result) 
 {
  mProgressDialog.dismiss(); 

 }


 private void unzipEntry(ZipFile zipfile, ZipEntry entry,String outputDir) throws IOException 
 {

  if (entry.isDirectory()) 
  {
   createDir(new File(outputDir, entry.getName()));
   return;
  }

  File outputFile = new File(outputDir, entry.getName());
  if (!outputFile.getParentFile().exists())
  {
   createDir(outputFile.getParentFile());
  }

  // Log.v("", "Extracting: " + entry);
  BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
  BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

  try 
  {

  }
  finally 
  {
   outputStream.flush();
   outputStream.close();
   inputStream.close();
  }
 }

 private void createDir(File dir) 
 {
  if (dir.exists()) 
  {
   return;
  }
  if (!dir.mkdirs()) 
  {
   throw new RuntimeException("Can not create dir " + dir);
  }
 }}
}

Note: Do not forgot to add below  permission in android Manifest.xml file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

21 Aug 2013

Crop image in circular shape in android

Hello Friends,

Today i am sharing  cropping an image and convert it into circular shape. Following Class will helps you to convert an image into circular shape.



There is two method i am posting here for cropping rounded images.


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

public class GraphicsUtil 
{ 
 public Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
  Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(output);

  final int color = 0xffff0000;
  final Paint paint = new Paint();
  final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
  final RectF rectF = new RectF(rect);

  paint.setAntiAlias(true);
  paint.setDither(true);
  paint.setFilterBitmap(true);
  canvas.drawARGB(0, 0, 0, 0);
  paint.setColor(color);
  canvas.drawOval(rectF, paint);

  paint.setColor(Color.BLUE);
  paint.setStyle(Paint.Style.STROKE);
  paint.setStrokeWidth((float) 4);
  paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
  canvas.drawBitmap(bitmap, rect, rect, paint);

  return output;
 }

 public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
  int targetWidth = 125;
  int targetHeight = 125;
  Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
    targetHeight,Bitmap.Config.ARGB_8888);

  Canvas canvas = new Canvas(targetBitmap);
  Path path = new Path();
  path.addCircle(((float) targetWidth - 1) / 2,
    ((float) targetHeight - 1) / 2,
    (Math.min(((float) targetWidth), 
      ((float) targetHeight)) / 2),
      Path.Direction.CCW);

  canvas.clipPath(path);
  Bitmap sourceBitmap = scaleBitmapImage;
  canvas.drawBitmap(sourceBitmap, 
    new Rect(0, 0, sourceBitmap.getWidth(),
      sourceBitmap.getHeight()), 
      new Rect(0, 0, targetWidth,
        targetHeight), null);
  return targetBitmap;
 }

}

MainActivity.Class
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener 
{

 // keep track of camera capture intent
 final int CAMERA_CAPTURE = 1;
 // keep track of cropping intent
 final int PIC_CROP = 2;
 // captured picture uri
 private Uri picUri;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // retrieve a reference to the UI button
  Button captureBtn = (Button) findViewById(R.id.capture_btn);
  // handle button clicks
  captureBtn.setOnClickListener(this);
 }

 /**
  * Click method to handle user pressing button to launch camera
  */
 public void onClick(View v) 
 {
  if (v.getId() == R.id.capture_btn) 
  {
   try 
   {
    // use standard intent to capture an image
    Intent captureIntent = new Intent(
      MediaStore.ACTION_IMAGE_CAPTURE);
    // we will handle the returned data in onActivityResult
    startActivityForResult(captureIntent, CAMERA_CAPTURE);
   }
   catch (ActivityNotFoundException anfe) 
   {
    // display an error message
    String errorMessage = "Whoops - your device doesn't support capturing images!";
    Toast toast = Toast.makeText(this, errorMessage,Toast.LENGTH_SHORT);
    toast.show();
   }
  }
 }

 /**
  * Handle user returning from both capturing and cropping the image
  */
 protected void onActivityResult(int requestCode, int resultCode, Intent data)
 {
  if (resultCode == RESULT_OK) 
  {
   // user is returning from capturing an image using the camera
   if (requestCode == CAMERA_CAPTURE) 
   {
    // get the Uri for the captured image
    picUri = data.getData();
    // carry out the crop operation
    performCrop();
   }
   // user is returning from cropping the image
   else if (requestCode == PIC_CROP) 
   {
    // get the returned data
    Bundle extras = data.getExtras();
    // get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");
    // retrieve a reference to the ImageView
    ImageView picView = (ImageView) findViewById(R.id.picture);
    // display the returned cropped image

    GraphicsUtil graphicUtil = new GraphicsUtil();
    //picView.setImageBitmap(graphicUtil.getRoundedShape(thePic));
    picView.setImageBitmap(graphicUtil.getCircleBitmap(thePic, 16));
   }
  }
 }

 /**
  * Helper method to carry out crop operation
  */
 private void performCrop() 
 {
  // take care of exceptions
  try {
   // call the standard crop action intent (the user device may not
   // support it)
   Intent cropIntent = new Intent("com.android.camera.action.CROP");
   // indicate image type and Uri
   cropIntent.setDataAndType(picUri, "image/*");
   // set crop properties
   cropIntent.putExtra("crop", "true");
   // indicate aspect of desired crop
   cropIntent.putExtra("aspectX", 1);
   cropIntent.putExtra("aspectY", 1);
   // indicate output X and Y
   cropIntent.putExtra("outputX", 256);
   cropIntent.putExtra("outputY", 256);
   // retrieve data on return
   cropIntent.putExtra("return-data", true);
   // start the activity - we handle returning in onActivityResult
   startActivityForResult(cropIntent, PIC_CROP);
  }
  // respond to users whose devices do not support the crop action
  catch (ActivityNotFoundException anfe) {
   // display an error message
   String errorMessage = "Whoops - your device doesn't support the crop action!";
   Toast toast = Toast
     .makeText(this, errorMessage, Toast.LENGTH_SHORT);
   toast.show();
  }
 }
}

More reference link

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

23 Jul 2013

DremelAnimation in Android

Hello friends, today i am going to post DremelAnimation in android.



Download full source code from here DremelAnimation

i will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

22 Jul 2013

QuickAction dialog in android.

Hello Fiends,

Quick Actions are basically actions/functions in a popup bar that are triggered by specific visual elements/buttons/items on the screen. Quick Actions are used to display contextual actions typically used in list views but not limited to it.


Download source code from here : QuickActionDemo


i will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

Page curl effect in Android

The android-page-curl is a 2D View which simulates a page curl effect.




Download source code

16 Jul 2013

CarouselAnimation in Android

Hello friends, today i am going to post CarouselAnimation in Android


Download source code

Cover Flow Animation in Android.

Hello, Friend today i am going to post Coverflow animation sample code.



CoverFlow.java
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;
import android.widget.ImageView;

@SuppressWarnings("deprecation")
public class CoverFlow extends Gallery 
{
/**
* Graphics Camera used for transforming the matrix of ImageViews
*/
private Camera mCamera = new Camera();

/**
* The maximum angle the Child ImageView will be rotated by
*/
private int mMaxRotationAngle = 60;

/**
* The maximum zoom on the centre Child
*/
private int mMaxZoom = -120;

/**
* The Centre of the Coverflow
*/
private int mCoveflowCenter;

public CoverFlow(Context context) {
super(context);
this.setStaticTransformationsEnabled(true);
this.setBackgroundColor(Color.BLACK);
}

public CoverFlow(Context context, AttributeSet attrs) {
super(context, attrs);
this.setStaticTransformationsEnabled(true);
this.setBackgroundColor(Color.BLACK);
}

public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setStaticTransformationsEnabled(true);
this.setBackgroundColor(Color.BLACK);
}

/**
* Get the max rotational angle of the image
* @return the mMaxRotationAngle
*/
public int getMaxRotationAngle() {
return mMaxRotationAngle;
}

/**
* Set the max rotational angle of each image
* @param maxRotationAngle
*            the mMaxRotationAngle to set
*/
public void setMaxRotationAngle(int maxRotationAngle) {
mMaxRotationAngle = maxRotationAngle;
}

/**
* Get the Max zoom of the centre image
* @return the mMaxZoom
*/
public int getMaxZoom() {
return mMaxZoom;
}

/**
* Set the max zoom of the centre image
* @param maxZoom
*            the mMaxZoom to set
*/
public void setMaxZoom(int maxZoom) {
mMaxZoom = maxZoom;
}

/**
* Get the Centre of the Coverflow
* @return The centre of this Coverflow.
*/
private int getCenterOfCoverflow() {
return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
+ getPaddingLeft();
}

/**
* Get the Centre of the View
* @return The centre of the given view.
*/
private static int getCenterOfView(View view) {
return view.getLeft() + view.getWidth() / 2;
}

/**
* {@inheritDoc}
* @see #setStaticTransformationsEnabled(boolean)
*/
protected boolean getChildStaticTransformation(View child, Transformation t) {

final int childCenter = getCenterOfView(child);
final int childWidth = child.getWidth();
int rotationAngle = 0;

t.clear();
t.setTransformationType(Transformation.TYPE_MATRIX);

if (childCenter == mCoveflowCenter) {
transformImageBitmap((ImageView) child, t, 0);
} else {
rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
if (Math.abs(rotationAngle) > mMaxRotationAngle) {
rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
: mMaxRotationAngle;
}
transformImageBitmap((ImageView) child, t, rotationAngle);
}

return true;
}

/**
* This is called during layout when the size of this view has changed. If
* you were just added to the view hierarchy, you're called with the old
* values of 0.
* @param w
*            Current width of this view.
* @param h
*            Current height of this view.
* @param oldw
*            Old width of this view.
* @param oldh
*            Old height of this view.
*/
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCoveflowCenter = getCenterOfCoverflow();
super.onSizeChanged(w, h, oldw, oldh);
}

/**
* Transform the Image Bitmap by the Angle passed
* @param imageView
*            ImageView the ImageView whose bitmap we want to rotate
* @param t
*            transformation
* @param rotationAngle
*            the Angle by which to rotate the Bitmap
*/
private void transformImageBitmap(ImageView child, Transformation t,
int rotationAngle) 
{
mCamera.save();
final Matrix imageMatrix = t.getMatrix();
;
final int imageHeight = child.getLayoutParams().height;
;
final int imageWidth = child.getLayoutParams().width;
final int rotation = Math.abs(rotationAngle);

mCamera.translate(0.0f, 0.0f, 100.0f);

// As the angle of the view gets less, zoom in
if (rotation < mMaxRotationAngle) 
{
float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
mCamera.translate(0.0f, 0.0f, zoomAmount);
}

mCamera.rotateY(rotationAngle);
mCamera.getMatrix(imageMatrix);
imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
mCamera.restore();
}
}

CoverFlowDemo.java
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class CoverFlowDemo extends Activity 
{

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);

CoverFlow coverFlow;
coverFlow = new CoverFlow(this);

coverFlow.setAdapter(new ImageAdapter(this));

ImageAdapter coverImageAdapter = new ImageAdapter(this);

coverFlow.setAdapter(coverImageAdapter);

coverFlow.setSpacing(-25);
coverFlow.setSelection(4, true);
coverFlow.setAnimationDuration(1000);

coverFlow.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView arg0, View arg1, int position,
long arg3) {
Toast.makeText(CoverFlowDemo.this, "" + position,
Toast.LENGTH_LONG).show();
}
});

setContentView(coverFlow);
}

public class ImageAdapter extends BaseAdapter 
{
int mGalleryItemBackground;
private Context mContext;

private Integer[] mImageIds = { R.drawable.android,
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4
};

private ImageView[] mImages;

public ImageAdapter(Context c) {
mContext = c;
mImages = new ImageView[mImageIds.length];
}

@SuppressWarnings("deprecation")
public boolean createReflectedImages() 
{
// The gap we want between the reflection and the original image
final int reflectionGap = 4;

int index = 0;
for (int imageId : mImageIds)
{
Bitmap originalImage = BitmapFactory.decodeResource(
getResources(), imageId);
int width = originalImage.getWidth();
int height = originalImage.getHeight();

// This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);

// Create a Bitmap with the flip matrix applied to it.
// We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
height / 2, width, height / 2, matrix, false);

// Create a new bitmap with same width but taller to fit
// reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
(height + height / 2), Config.ARGB_8888);

// Create a new Canvas with the bitmap that's big enough for
// the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
// Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
// Draw in the gap
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap,
deafaultPaint);
// Draw in the reflection
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap,
null);

// Create a shader that is a linear gradient that covers the
// reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0,
originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap,
0x70ffffff, 0x00ffffff, TileMode.CLAMP);
// Set the paint to use this shader (linear gradient)
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);

ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmapWithReflection);
android.widget.Gallery.LayoutParams imgLayout = new CoverFlow.LayoutParams(
320, 480);
imageView.setLayoutParams(imgLayout);
imageView.setPadding(30, 100, 20, 20);
mImages[index++] = imageView;

}
return true;
}

public int getCount() 
{
return mImageIds.length;
}

public Object getItem(int position) 
{
return position;
}

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

@SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent) 
{

// Use this code if you want to load from resources
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

// Make sure we set anti-aliasing otherwise we get jaggies
BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
drawable.setAntiAlias(true);
return i;

// return mImages[position];
}

/**
* Returns the size (0.0f to 1.0f) of the views depending on the
* 'offset' to the center.
*/
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}

}
}

14 Jun 2013

ListView-Swipe To Delete list in android.

Hello Friends, Here I am sharing a code to perform delete operation on listview  by just swiping it to right or left.


activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:padding="16dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            style="?android:listSeparatorTextViewStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ListView" />

        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>


</LinearLayout>

SwipeDismissListViewTouchListener:

import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;

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

import static com.nineoldandroids.view.ViewHelper.setAlpha;
import static com.nineoldandroids.view.ViewHelper.setTranslationX;
import static com.nineoldandroids.view.ViewPropertyAnimator.animate;

public class SwipeDismissListViewTouchListener implements View.OnTouchListener {

    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private ListView mListView;
    private OnDismissCallback mCallback;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
    private int mDismissAnimationRefCount = 0;
    private float mDownX;
    private boolean mSwiping;
    private VelocityTracker mVelocityTracker;
    private int mDownPosition;
    private View mDownView;
    private boolean mPaused;

    public interface OnDismissCallback {
    
        void onDismiss(ListView listView, int[] reverseSortedPositions);
    }

 
    public SwipeDismissListViewTouchListener(ListView listView, OnDismissCallback callback) {
        ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = listView.getContext().getResources().getInteger(
                android.R.integer.config_shortAnimTime);
        mListView = listView;
        mCallback = callback;
    }

  
    public void setEnabled(boolean enabled) {
        mPaused = !enabled;
    }

  
    public AbsListView.OnScrollListener makeScrollListener() {
        return new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        };
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (mViewWidth < 2) {
            mViewWidth = mListView.getWidth();
        }

        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                if (mPaused) {
                    return false;
                }            

                // Find the child view that was touched (perform a hit test)
                Rect rect = new Rect();
                int childCount = mListView.getChildCount();
                int[] listViewCoords = new int[2];
                mListView.getLocationOnScreen(listViewCoords);
                int x = (int) motionEvent.getRawX() - listViewCoords[0];
                int y = (int) motionEvent.getRawY() - listViewCoords[1];
                View child;
                for (int i = 0; i < childCount; i++) {
                    child = mListView.getChildAt(i);
                    child.getHitRect(rect);
                    if (rect.contains(x, y)) {
                        mDownView = child;
                        break;
                    }
                }

                if (mDownView != null) {
                    mDownX = motionEvent.getRawX();
                    mDownPosition = mListView.getPositionForView(mDownView);

                    mVelocityTracker = VelocityTracker.obtain();
                    mVelocityTracker.addMovement(motionEvent);
                }
                view.onTouchEvent(motionEvent);
                return true;
            }

            case MotionEvent.ACTION_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = motionEvent.getRawX() - mDownX;
                mVelocityTracker.addMovement(motionEvent);
                mVelocityTracker.computeCurrentVelocity(1000);
                float velocityX = Math.abs(mVelocityTracker.getXVelocity());
                float velocityY = Math.abs(mVelocityTracker.getYVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / 2) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
                        && velocityY < velocityX) {
                    dismiss = true;
                    dismissRight = mVelocityTracker.getXVelocity() > 0;
                }
                if (dismiss) {
                    // dismiss
                    final View downView = mDownView; // mDownView gets null'd before animation ends
                    final int downPosition = mDownPosition;
                    ++mDismissAnimationRefCount;
                    animate(mDownView)
                            .translationX(dismissRight ? mViewWidth : -mViewWidth)
                            .alpha(0)
                            .setDuration(mAnimationTime)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    performDismiss(downView, downPosition);
                                }
                            });
                } else {
                    // cancel
                    animate(mDownView)
                            .translationX(0)
                            .alpha(1)
                            .setDuration(mAnimationTime)
                            .setListener(null);
                }
                mVelocityTracker = null;
                mDownX = 0;
                mDownView = null;
                mDownPosition = ListView.INVALID_POSITION;
                mSwiping = false;
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                if (mVelocityTracker == null || mPaused) {
                    break;
                }

                mVelocityTracker.addMovement(motionEvent);
                float deltaX = motionEvent.getRawX() - mDownX;
                if (Math.abs(deltaX) > mSlop) {
                    mSwiping = true;
                    mListView.requestDisallowInterceptTouchEvent(true);

                    // Cancel ListView's touch (un-highlighting the item)
                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                            (motionEvent.getActionIndex()
                                    << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    mListView.onTouchEvent(cancelEvent);
                }

                if (mSwiping) {
                    setTranslationX(mDownView, deltaX);
                    setAlpha(mDownView, Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }
        }
        return false;
    }

    class PendingDismissData implements Comparable<PendingDismissData> {
        public int position;
        public View view;

        public PendingDismissData(int position, View view) {
            this.position = position;
            this.view = view;
        }

        @Override
        public int compareTo(PendingDismissData other) {
            // Sort by descending position
            return other.position - position;
        }
    }

    private void performDismiss(final View dismissView, final int dismissPosition) {
        // Animate the dismissed list item to zero-height and fire the dismiss callback when
        // all dismissed list item animations have completed. This triggers layout on each animation
        // frame; in the future we may want to do something smarter and more performant.

        final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
        final int originalHeight = dismissView.getHeight();

        ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                --mDismissAnimationRefCount;
                if (mDismissAnimationRefCount == 0) {
                    // No active animations, process all pending dismisses.
                    // Sort by descending position
                    Collections.sort(mPendingDismisses);

                    int[] dismissPositions = new int[mPendingDismisses.size()];
                    for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
                        dismissPositions[i] = mPendingDismisses.get(i).position;
                    }
                    mCallback.onDismiss(mListView, dismissPositions);

                    ViewGroup.LayoutParams lp;
                    for (PendingDismissData pendingDismiss : mPendingDismisses) {
                        // Reset view presentation
                        setAlpha(pendingDismiss.view, 1f);
                        setTranslationX(pendingDismiss.view, 0);
                        lp = pendingDismiss.view.getLayoutParams();
                        lp.height = originalHeight;
                        pendingDismiss.view.setLayoutParams(lp);
                    }

                    mPendingDismisses.clear();
                }
            }
        });

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                lp.height = (Integer) valueAnimator.getAnimatedValue();
                dismissView.setLayoutParams(lp);
            }
        });

        mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
        animator.start();
    }
}

SwipeDismissTouchListener:

import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;
import static com.nineoldandroids.view.ViewHelper.setAlpha;
import static com.nineoldandroids.view.ViewHelper.setTranslationX;
import static com.nineoldandroids.view.ViewPropertyAnimator.animate;


public class SwipeDismissTouchListener implements View.OnTouchListener {
    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private View mView;
    private OnDismissCallback mCallback;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private float mDownX;
    private boolean mSwiping;
    private Object mToken;
    private VelocityTracker mVelocityTracker;
    private float mTranslationX;

  
    public interface OnDismissCallback {
     
        void onDismiss(View view, Object token);
    }

 
    public SwipeDismissTouchListener(View view, Object token, OnDismissCallback callback) {
        ViewConfiguration vc = ViewConfiguration.get(view.getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = view.getContext().getResources().getInteger(
                android.R.integer.config_shortAnimTime);
        mView = view;
        mToken = token;
        mCallback = callback;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        // offset because the view is translated during swipe
        motionEvent.offsetLocation(mTranslationX, 0);

        if (mViewWidth < 2) {
            mViewWidth = mView.getWidth();
        }

        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                // TODO: ensure this is a finger, and set a flag
                mDownX = motionEvent.getRawX();
                mVelocityTracker = VelocityTracker.obtain();
                mVelocityTracker.addMovement(motionEvent);
                view.onTouchEvent(motionEvent);
                return false;
            }

            case MotionEvent.ACTION_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = motionEvent.getRawX() - mDownX;
                mVelocityTracker.addMovement(motionEvent);
                mVelocityTracker.computeCurrentVelocity(1000);
                float velocityX = Math.abs(mVelocityTracker.getXVelocity());
                float velocityY = Math.abs(mVelocityTracker.getYVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / 2) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
                        && velocityY < velocityX) {
                    dismiss = true;
                    dismissRight = mVelocityTracker.getXVelocity() > 0;
                }
                if (dismiss) {
                    // dismiss
                    animate(mView)
                            .translationX(dismissRight ? mViewWidth : -mViewWidth)
                            .alpha(0)
                            .setDuration(mAnimationTime)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    performDismiss();
                                }
                            });
                } else {
                    // cancel
                    animate(mView)
                            .translationX(0)
                            .alpha(1)
                            .setDuration(mAnimationTime)
                            .setListener(null);
                }
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mSwiping = false;
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                if (mVelocityTracker == null) {
                    break;
                }

                mVelocityTracker.addMovement(motionEvent);
                float deltaX = motionEvent.getRawX() - mDownX;
                if (Math.abs(deltaX) > mSlop) {
                    mSwiping = true;
                    mView.getParent().requestDisallowInterceptTouchEvent(true);

                    // Cancel listview's touch
                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                        (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    mView.onTouchEvent(cancelEvent);
                }

                if (mSwiping) {
                    mTranslationX = deltaX;
                    setTranslationX(mView, deltaX);
                    // TODO: use an ease-out interpolator or such
                    setAlpha(mView, Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }
        }
        return false;
    }

    private void performDismiss() {
        // Animate the dismissed view to zero-height and then fire the dismiss callback.
        // This triggers layout on each animation frame; in the future we may want to do something
        // smarter and more performant.

        final ViewGroup.LayoutParams lp = mView.getLayoutParams();
        final int originalHeight = mView.getHeight();

        ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mCallback.onDismiss(mView, mToken);
                // Reset view presentation
                setAlpha(mView, 1f);
                setTranslationX(mView, 0);
                lp.height = originalHeight;
                mView.setLayoutParams(lp);
            }
        });

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                lp.height = (Integer) valueAnimator.getAnimatedValue();
                mView.setLayoutParams(lp);
            }
        });

        animator.start();
    }
}


MainActivity:

import java.util.ArrayList;
import java.util.Arrays;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity
{
    ArrayAdapter<String> mAdapter;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set up ListView example
        String[] items = new String[20];
        for (int i = 0; i < items.length; i++)
        {
            items[i] = "Item " + (i + 1);
        }

        mAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                new ArrayList<String>(Arrays.asList(items)));
        setListAdapter(mAdapter);

        ListView listView = getListView();
        // Create a ListView-specific touch listener. ListViews are given special treatment because
        // by default they handle touches for their list items... i.e. they're in charge of drawing
        // the pressed state (the list selector), handling list item clicks, etc.
        SwipeDismissListViewTouchListener touchListener =
                new SwipeDismissListViewTouchListener(
                        listView,
                        new SwipeDismissListViewTouchListener.OnDismissCallback() {
                            @Override
                            public void onDismiss(ListView listView, int[] reverseSortedPositions) {
                                for (int position : reverseSortedPositions) {
                                    mAdapter.remove(mAdapter.getItem(position));
                                }
                                mAdapter.notifyDataSetChanged();
                            }
                        });
        listView.setOnTouchListener(touchListener);
        // Setting this scroll listener is required to ensure that during ListView scrolling,
        // we don't look for swipes.
        listView.setOnScrollListener(touchListener.makeScrollListener());    
      
    }

    @Override
    protected void onListItemClick(ListView listView, View view, int position, long id)
    {
        Toast.makeText(this,
                "Clicked " + getListAdapter().getItem(position).toString(),
                Toast.LENGTH_SHORT).show();
    }
}
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)