Friday, 28 September 2012

Image CoverFlow in android

All Image from SD card show in Cover Flow style in android
create android project and add this two file and also in Androidmainfest.xml file set mainactivity is CoverflowExample.java
in src/ folder

1.  Coverflow.java

package com.prashant.coverflow;

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

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

 public Coverflow(Context context, AttributeSet attrs) {
  super(context, attrs);
        this.setStaticTransformationsEnabled(true);
 }

  public Coverflow(Context context, AttributeSet attrs, int defStyle) {
   super(context, attrs, defStyle);
   this.setStaticTransformationsEnabled(true);  
  }
 
    /**
     * 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();
 }
}


2.CoverflowExample.java

package com.prashant.coverflow;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class CoverflowExample extends Activity {
private Cursor cursor;
private int columnIndex;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
   
     Coverflow coverFlow;
     coverFlow = new Coverflow(this);
     String[] projection = {MediaStore.Images.Thumbnails._ID};
     cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
             projection, // Which columns to return
             null,       // Return all rows
             null,
             MediaStore.Images.Thumbnails.IMAGE_ID);
     columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

coverFlow.setAdapter(new ImageAdapter(this));
     coverFlow.setSpacing(-25);
     coverFlow.setSelection(4, true);
     coverFlow.setAnimationDuration(1000);
     setContentView(coverFlow);
    }
 
 

public class ImageAdapter extends BaseAdapter {
     int mGalleryItemBackground;
     private Context mContext;
     public ImageAdapter(Context c) {
         mContext = c;
     }
     public int getCount() {
         return cursor.getCount();
     }

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

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

     public View getView(int position, View convertView, ViewGroup parent) {

      //Use this code if you want to load from resources
         ImageView i = new ImageView(mContext);
       
         if (convertView == null) {
             i = new ImageView(mContext);
             // Move cursor to current position
             cursor.moveToPosition(position);
             // Get the current value for the requested column
             int imageID = cursor.getInt(columnIndex);
             // Set the content of the image based on the provided URI
             i.setImageURI(Uri.withAppendedPath(
                     MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
             i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
           //  i.setPadding(8, 8, 8, 8);
             i.setLayoutParams(new Coverflow.LayoutParams(250, 250));
         }
         else {
             i = (ImageView)convertView;
         }
         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) {
          return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
      }

 }
}

OUTPUT:
Download source code Here...


Wednesday, 19 September 2012

Loading Screen

Loading Screen:

1.src: Loading.java


package com.prashant.loadscreen;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class Loading extends Activity
{
private ViewSwitcher viewSwitcher;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        new LoadViewTask().execute();
    }
   
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>
    {
    private TextView tv_progress;
    private ProgressBar pb_progressBar;
   
    //Before running code in the separate thread
@Override
protected void onPreExecute()
{
//Initialize the ViewSwitcher object
       viewSwitcher = new ViewSwitcher(Loading.this);
       /* Initialize the loading screen with data from the 'loadingscreen.xml' layout xml file.
        * Add the initialized View to the viewSwitcher.*/
viewSwitcher.addView(ViewSwitcher.inflate(Loading.this, R.layout.loadingscreen, null));

//Initialize the TextView and ProgressBar instances - IMPORTANT: call findViewById() from viewSwitcher.
tv_progress = (TextView) viewSwitcher.findViewById(R.id.tv_progress);
pb_progressBar = (ProgressBar) viewSwitcher.findViewById(R.id.pb_progressbar);
//Sets the maximum value of the progress bar to 100
pb_progressBar.setMax(100);

//Set ViewSwitcher instance as the current View.
setContentView(viewSwitcher);
}

//The code to be executed in a background thread.
@Override
protected Void doInBackground(Void... params)
{
try
{
//Get the current thread's token
synchronized (this)
{
//Initialize an integer (that will act as a counter) to zero
int counter = 0;
//While the counter is smaller than four
while(counter <= 4)
{
this.wait(1500);
//Increment the counter
counter++;
publishProgress(counter*10);//setting the time interval of the progeress bar
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}

//Update the TextView and the progress at progress bar
@Override
protected void onProgressUpdate(Integer... values)
{
//Update the progress at the UI if progress value is smaller than 100
if(values[0] <= 100)
{
tv_progress.setText("Progress: " + Integer.toString(values[0]) + "%");
pb_progressBar.setProgress(values[0]);
}
}

//After executing the code in the thread
@Override
protected void onPostExecute(Void result)
{
/* Initialize the application's main interface from the 'main.xml' layout xml file.
        * Add the initialized View to the viewSwitcher.*/
viewSwitcher.addView(ViewSwitcher.inflate(Loading.this, R.layout.main, null));
//Switch the Views
viewSwitcher.showNext();
}
    }
   
    //Override the default back key behavior
    @Override
    public void onBackPressed()
    {
    //Emulate the progressDialog.setCancelable(false) behavior
    //If the first view is being shown
    if(viewSwitcher.getDisplayedChild() == 0)
    {
    //Do nothing
    return;
    }
    else
    {
    //Finishes the current Activity
    super.onBackPressed();
    }
    }
}


2.res--drawable--
2.1loadingscreenbg.xml


<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/tile"
android:tileMode="repeat" />
2.2 tile.png

3.res--layout
3.1 loadingscreen.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/loadingscreenbg">

    <ProgressBar
        android:id="@+id/pb_progressbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dip"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="10dip"/>

    <TextView
        android:id="@+id/tv_loadingtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/pb_progressbar"
        android:layout_centerHorizontal="true"
        android:text="Loading, please wait..."
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/tv_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/pb_progressbar"
        android:layout_centerHorizontal="true"
        android:text="Progress: 0%"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#ffffffff" android:shadowColor="#000000"
        android:shadowDx="2.0" android:shadowDy="2.0"
        android:shadowRadius="3.0"/>

</RelativeLayout>

3.2 main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
android:layout_width="match_parent"
android:background="#B0B6BA"
    >
<TextView
    android:id="@+id/RLayout1tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"      
        android:textColor="#688CBE"
        android:textSize="15dp"
        android:textStyle="bold"      
        android:layout_centerInParent="true"
   android:text="Screen load successfully"
    />
</RelativeLayout>



output:1.
2.