Saturday, 23 July 2016

Rounded or Circle ImageView with Shadow in Android




RoundedImageViewShadow.java

public class RoundedImageViewShadow extends ImageView {

    private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;

    // Default Values
    private static final float DEFAULT_BORDER_WIDTH = 4;
    private static final float DEFAULT_SHADOW_RADIUS = 8.0f;

    // Properties
    private float borderWidth;
    private int canvasSize;
    private float shadowRadius;
    private int shadowColor = Color.BLACK;

    // Object used to draw
    private Bitmap image;
    private Drawable drawable;
    private Paint paint;
    private Paint paintBorder;

    //region Constructor & Init Method
    public RoundedImageViewShadow(final Context context) {
        this(context, null);
    }

    public RoundedImageViewShadow(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundedImageViewShadow(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        // Init paint
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        paintBorder.setAntiAlias(true);

        // Load the styled attributes and set their properties
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyleAttr, 0);

        // Init Border
        if (attributes.getBoolean(R.styleable.CircularImageView_civ_border, true)) {
            float defaultBorderSize = DEFAULT_BORDER_WIDTH * getContext().getResources().getDisplayMetrics().density;
            setBorderWidth(attributes.getDimension(R.styleable.CircularImageView_civ_border_width, defaultBorderSize));
            setBorderColor(attributes.getColor(R.styleable.CircularImageView_civ_border_color, Color.WHITE));
        }

        // Init Shadow
        if (attributes.getBoolean(R.styleable.CircularImageView_civ_shadow, false)) {
            shadowRadius = DEFAULT_SHADOW_RADIUS;
            drawShadow(attributes.getFloat(R.styleable.CircularImageView_civ_shadow_radius, shadowRadius), attributes.getColor(R.styleable.CircularImageView_civ_shadow_color, shadowColor));
        }
    }
    //endregion

    //region Set Attr Method
    public void setBorderWidth(float borderWidth) {
        this.borderWidth = borderWidth;
        requestLayout();
        invalidate();
    }

    public void setBorderColor(int borderColor) {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);
        invalidate();
    }

    public void addShadow() {
        if (shadowRadius == 0)
            shadowRadius = DEFAULT_SHADOW_RADIUS;
        drawShadow(shadowRadius, shadowColor);
        invalidate();
    }

    public void setShadowRadius(float shadowRadius) {
        drawShadow(shadowRadius, shadowColor);
        invalidate();
    }

    public void setShadowColor(int shadowColor) {
        drawShadow(shadowRadius, shadowColor);
        invalidate();
    }

    @Override
    public ScaleType getScaleType() {
        return SCALE_TYPE;
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (scaleType != SCALE_TYPE) {
            throw new IllegalArgumentException(String.format("ScaleType %s not supported. ScaleType.CENTER_CROP is used by default. So you don't need to use ScaleType.", scaleType));
        }
    }
    //endregion

    //region Draw Method
    @Override
    public void onDraw(Canvas canvas) {
        // Load the bitmap
        loadBitmap();

        // Check if image isn't null
        if (image == null)
            return;

        if (!isInEditMode()) {
            canvasSize = canvas.getWidth();
            if (canvas.getHeight() < canvasSize) {
                canvasSize = canvas.getHeight();
            }
        }

        // circleCenter is the x or y of the view's center
        // radius is the radius in pixels of the cirle to be drawn
        // paint contains the shader that will texture the shape
        int circleCenter = (int) (canvasSize - (borderWidth * 2)) / 2;
        // Draw Border
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - (shadowRadius + shadowRadius / 2), paintBorder);
        // Draw CircularImageView
        canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - (shadowRadius + shadowRadius / 2), paint);
    }

    private void loadBitmap() {
        if (this.drawable == getDrawable())
            return;

        this.drawable = getDrawable();
        this.image = drawableToBitmap(this.drawable);
        updateShader();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        canvasSize = w;
        if (h < canvasSize)
            canvasSize = h;
        if (image != null)
            updateShader();
    }

    private void drawShadow(float shadowRadius, int shadowColor) {
        this.shadowRadius = shadowRadius;
        this.shadowColor = shadowColor;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        }
        paintBorder.setShadowLayer(shadowRadius, 0.0f, shadowRadius / 2, shadowColor);
    }

    private void updateShader() {
        if (image == null)
            return;

        // Crop Center Image
        image = cropBitmap(image);

        // Create Shader
        BitmapShader shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        // Center Image in Shader
        Matrix matrix = new Matrix();
        matrix.setScale((float) canvasSize / (float) image.getWidth(), (float) canvasSize / (float) image.getHeight());
        shader.setLocalMatrix(matrix);

        // Set Shader in Paint
        paint.setShader(shader);
    }

    private Bitmap cropBitmap(Bitmap bitmap) {
        Bitmap bmp;
        if (bitmap.getWidth() >= bitmap.getHeight()) {
            bmp = Bitmap.createBitmap(
                    bitmap,
                    bitmap.getWidth() / 2 - bitmap.getHeight() / 2,
                    0,
                    bitmap.getHeight(), bitmap.getHeight());
        } else {
            bmp = Bitmap.createBitmap(
                    bitmap,
                    0,
                    bitmap.getHeight() / 2 - bitmap.getWidth() / 2,
                    bitmap.getWidth(), bitmap.getWidth());
        }
        return bmp;
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        } else if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int intrinsicWidth = drawable.getIntrinsicWidth();
        int intrinsicHeight = drawable.getIntrinsicHeight();

        if (!(intrinsicWidth > 0 && intrinsicHeight > 0))
            return null;

        try {
            // Create Bitmap object out of the drawable
            Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            // Simply return null of failed bitmap creations
            Log.e(getClass().toString(), "Encountered OutOfMemoryError while generating bitmap!");
            return null;
        }
    }
    //endregion

    //region Mesure Method
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // The parent has determined an exact size for the child.
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // The parent has not imposed any constraint on the child.
            result = canvasSize;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // Measure the text (beware: ascent is a negative number)
            result = canvasSize;
        }

        return (result + 2);
    }
    //endregion
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.imageshadows.MainActivity">


    <RelativeLayout
        android:id="@+id/relative_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <com.imageshadows.RoundedImageViewShadow
            android:id="@+id/img_with_shadows"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/pro_pic_one"
            app:civ_border_color="#EEEEEE"
            app:civ_border_width="0dp"
            app:civ_shadow="true"
            app:civ_shadow_color="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/img_with_shadows"
            android:text="Round Image with shadow" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relative_second"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/relative_one"
        android:layout_marginTop="10dp"
        android:gravity="center">

        <ImageView
            android:id="@+id/img_without_shadows"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/pro_pic_one" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/img_without_shadows"
            android:text="Round Image without shadow" />
    </RelativeLayout>

</RelativeLayout>


attrs.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="CircularImageView">
        <attr name="civ_border" format="boolean"/>
        <attr name="civ_border_width" format="dimension"/>
        <attr name="civ_border_color" format="color"/>
        <attr name="civ_shadow" format="boolean"/>
        <attr name="civ_shadow_color" format="color"/>
        <attr name="civ_shadow_radius" format="float"/>
    </declare-styleable>

</resources>



Thursday, 12 December 2013

Insert data in android using Sqlite

RegistrationActivity.java

package com.Registration;

import com.AppDemo.R;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegistrationActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    DBAdapter db;
    // Declare variables
    EditText fname;
    EditText lname;
    EditText dob;
    EditText address;
    EditText mobile;
    EditText email;


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

        // Get the resource
        fname = (EditText) findViewById(R.id.edt_Fname);
        lname = (EditText) findViewById(R.id.edt_Lnamme);
        dob = (EditText) findViewById(R.id.edt_Dob);
        address = (EditText) findViewById(R.id.edt_Address);
        mobile = (EditText) findViewById(R.id.edt_Mobile);
        email = (EditText) findViewById(R.id.edt_Email);

        Button submit = (Button) findViewById(R.id.btn_add);
        Button contact = (Button) findViewById(R.id.btn_addcontact);
        submit.setOnClickListener(this);
        contact.setOnClickListener(this);
       
        db = new DBAdapter(this);

        getData();
    }

    private void addData(String fname, String lname, String dob,
            String address, String mobile, String email) {
        // TODO Auto-generated method stub
        db.open();
        if (db.insertContact(fname, lname, dob, address, mobile, email) >= 0) {
            Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
        }
        db.close();
    }

    private void getData() {
        // TODO Auto-generated method stub
        db.open();
        Cursor c = db.getAllContacts();
        if (c.moveToFirst()) {
            do {
                DisplayContact(c);
            } while (c.moveToNext());
        }
    }

    public void DisplayContact(Cursor c) {
        Toast.makeText(
                this,
                "Id: " + c.getString(0) + "\n" + "FName: " + c.getString(1)
                        + "\n" + "LName: " + c.getString(2) + "\n" + "DOB: "
                        + c.getString(3) + "\n" + "Address: " + c.getString(4)
                        + "\n" + "Mobile :" + c.getString(5) + "\n" + "Email: "
                        + c.getString(6), Toast.LENGTH_LONG).show();
    }

   
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_add:
           
            String name = fname.getText().toString();
            String surname = lname.getText().toString();
            String dobirth = dob.getText().toString();
           
            String addres = address.getText().toString();
            String mobileno = mobile.getText().toString();
            String email_id = email.getText().toString();
           
            Toast.makeText(
                    RegistrationActivity.this,
                    "Name: " + name + "\n" + "Lname: " + surname + "\n" + "DOB: "
                            + dobirth + "\n" + "Address: " + addres + "\n"
                            + "Mob: " + mobileno + "\n" + "Email: " + email_id
                            + "\n", Toast.LENGTH_LONG).show();
            addData(name, surname, dobirth, addres, mobileno, email_id);

            name = "";
            surname = "";
            dobirth = "";
            addres = "";
            mobileno = "";
            email_id = "";
           
            break;

        case R.id.btn_addcontact:
            startActivity(new Intent(RegistrationActivity.this, Calculation.class));
            break;
        default:
            break;
        }
    }
}

DBAdapter.java

package com.Registration;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "id";
    static final String KEY_FNAME = "fname";
    static final String KEY_LNAME = "lname";
    static final String KEY_DATE_OF_BIRTH = "dob";
    static final String KEY_CREATED_ON_DATE = "created_on";
    static final String KEY_ADDRESS = "address";
    static final String KEY_MOBILE = "mobile";
    static final String KEY_EMAIL = "email";
   
   
    static final String KEY_CAL_ID = "cal_id";
    static final String KEY_CAL_TITAL = "cal_tital";
    static final String KEY_CAL_DESCRIPTION = "ccal_description";
    static final String KEY_CAL_CREATED_DATE = "cal_created_date";
    static final String KEY_CAL_EXP_DATE = "cal_expiry_date";
   
   
    static final String TAG = "DBAdapter";
    static final String DATABASE_NAME = "Personal";
    static final String DATABASE_REGISTRATION_TABLE = "Registration";
    static final String DATABASE_CALCULATION_TABLE = "Calculation";
    static final int DATABASE_VERSION = 1;
   
    /*public void onCreate(SQLiteDatabase db) {
        String CREATE_REGISTRATION_TABLE = "CREATE TABLE " + DATABASE_REGISTRATION_TABLE + "("
                + KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_FNAME + " TEXT," + KEY_LNAME + "TEXT,"+ KEY_ADDRESS + "TEXT,"
                + KEY_MOBILE + " TEXT," +  KEY_EMAIL + " TEXT" +")";
        db.execSQL(DATABASE_REGISTRATION_TABLE);
    }*/
   
    static final String DATABASE_CREATE = "create table Registration (id integer primary key autoincrement, "
            + "fname text not null, lname text not null, dob text null, created_on text null, address text not null, mobile text not null, email text not null);";
   
    final Context context;
    DatabaseHelper DBHelper;
    SQLiteDatabase db;
    Calendar currentDate;
    SimpleDateFormat formatter;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
        formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS Registration");
            onCreate(db);
        }
    }

    // ---opens the database---
    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert a contact into the database---
    public long insertContact(String fname, String lname, String dob, String address, String mobile, String email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_FNAME, fname);
        initialValues.put(KEY_LNAME, lname);
        initialValues.put(KEY_DATE_OF_BIRTH, dob);
        //initialValues.put(KEY_CREATED_ON_DATE, formatter.format(currentDate.getTime()));
        initialValues.put(KEY_ADDRESS, address);
        initialValues.put(KEY_MOBILE, mobile);
        initialValues.put(KEY_EMAIL, email);
        return db.insert(DATABASE_REGISTRATION_TABLE, null, initialValues);
    }

    // ---deletes a particular contact---
    public boolean deleteContact(long rowId) {
        return db.delete(DATABASE_REGISTRATION_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    // ---retrieves all the contacts---
    public Cursor getAllContacts() {
        return db.query(DATABASE_REGISTRATION_TABLE, new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_DATE_OF_BIRTH, KEY_ADDRESS, KEY_MOBILE,
                KEY_EMAIL }, null, null, null, null, null);
    }

    // ---retrieves a particular contact---
    public Cursor getContact(long rowId) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_REGISTRATION_TABLE, new String[] {
                KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_DATE_OF_BIRTH, KEY_ADDRESS, KEY_MOBILE, KEY_EMAIL }, KEY_ROWID + "=" + rowId,
                null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    // ---updates a contact---
    public boolean updateContact(long rowId, String fname, String lname, String dob, String address, String mobile, String email) {
        ContentValues args = new ContentValues();
        args.put(KEY_FNAME, fname);
        args.put(KEY_LNAME, lname);
        args.put(KEY_DATE_OF_BIRTH, dob);
        args.put(KEY_ADDRESS, address);
        args.put(KEY_MOBILE, mobile);
        args.put(KEY_EMAIL, email);
       
        return db.update(DATABASE_REGISTRATION_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}


Thursday, 7 February 2013

Dynamically create button in android


MainActivity.java


public class MainActivity extends Activity { 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/** Call customButton Method */
customButton();
}

private void customButton() {
// TODO Auto-generated method stub
Button myButton = new Button(this);
myButton.setText("Click Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.btn_layout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Hello Friends", Toast.LENGTH_LONG).show();
}
});
}
}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/dynamic"
    android:orientation="vertical"
    tools:context=".MainActivity" >

 <LinearLayout
        android:id="@+id/btn_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </LinearLayout>

</LinearLayout>

Friday, 4 January 2013

Image zoomin and zoomout in android


Normal Image Screen


Zoomout Image Screen

Zoomin Image Screen

MainActivity.java

package com.example.image_zoomin_zoomout;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.FloatMath;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class MainActivity extends Activity  implements  OnTouchListener{

/**Variables Declaration*/
private static final String TAG = "Touch";
    @SuppressWarnings("unused")
    private static final float MIN_ZOOM = 1f,MAX_ZOOM = 1f;

    // These matrices will be used to scale points of the image
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();

    // The 3 states (events) which the user is trying to perform
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // these PointF objects are used to record the point(s) the user is touching
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist = 1f;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ImageView imv = (ImageView)findViewById(R.id.imageView1);
        imv.setOnTouchListener(this);
    }
    
    public boolean onTouch(View v, MotionEvent event)
    {
    ImageView imv = (ImageView) v ;
    imv.setScaleType(ImageView.ScaleType.MATRIX);
    float scale;
   
    dumpEvent(event);
   
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG,"Mode =Drage");
mode = DRAG;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode =NONE;
Log.d(TAG, "Mode = None");
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if(oldDist > 10f)
{
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) 
{
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
}
else if (mode == ZOOM) 
{
float newDist = spacing (event);
Log.d(TAG, "newDistance=" +newDist);
if (newDist > 5f) 
{
matrix.set(savedMatrix);
scale = newDist / oldDist;
// setting the scaling of the matrix...if scale > 1 means zoom in...if scale < 1 means zoom out
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;

}
    imv.setImageMatrix(matrix);
   
return true;
   
    }

/*
     * --------------------------------------------------------------------------
     * Method: spacing Parameters: MotionEvent Returns: float Description:
     * checks the spacing between the two fingers on touch
     * ----------------------------------------------------
     */
    
    private float spacing(MotionEvent event) {
// TODO Auto-generated method stub
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
   
    return FloatMath.sqrt(x * x + y *y);
}
    
    /*
     * --------------------------------------------------------------------------
     * Method: midPoint Parameters: PointF object, MotionEvent Returns: void
     * Description: calculates the midpoint between the two fingers
     * ------------------------------------------------------------
     */
    
    private void midPoint(PointF point, MotionEvent event) {
// TODO Auto-generated method stub
   
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
   
    point.set(x/2, y/2);    
    }
    
    /** Show an event in the LogCat view, for debugging */
private void dumpEvent(MotionEvent event) {
// TODO Auto-generated method stub
String names[] = {"DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE","POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new  StringBuilder();
int action = event.getAction();
int actionCode =  action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) 
{
sb.append("(paid").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) 
{
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
       sb.append(")=").append((int) event.getX(i));
       sb.append(",").append((int) event.getY(i));
           if (i + 1 < event.getPointerCount())
               sb.append(";");
}
sb.append("]");
        Log.d("Touch Events ---------", sb.toString());
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}


Layout : activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="422dp"
        android:src="@drawable/android" />

</LinearLayout>
Download : Source

Tuesday, 1 May 2012

External Fonts use in Android

ExternalFontActivity.java


Layout.main.xml

Assets : fonts


Note : Create a fonts folder under assets folder and place all your fonts file in it. (Folder name can be anything)

Wednesday, 25 April 2012

Tuesday, 17 April 2012

Export Phone Contacts CSV in Android

ContactlistActivity.java



Note : Give the Following permission in android menifest file.

AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Thursday, 12 April 2012

Custom Tital Bar in Android


Title_Bar_Color_ChangeActivity.java


Layout : Main.xml

Layout : titlebar.xml

Values : colors.xml


Values : styles.xml
Values : themes.xml

AndroidManifest.xml

Tuesday, 10 April 2012

10 Reasons why Android 4.0 (Ice Cream Sandwich) is better than Apple’s iOS

Google has finally figured out the recipe for success with the introduction of Ice Cream Sandwich, the newest member of Android OS family. Google has faced many criticisms around the responsiveness of the UI in Android. Many tech experts will conclude their reviews of the Android OS with statements like, “Android OS is the best mobile operating system besides iOS but it still suffers from occasional lag or stutter in the user interface”.



Android 4.0 (Ice Cream Sandwich) is the latest version of the Android platform for phones, tablets, and more. This version of Android unifies everything by combining the Phone and Tablet software in one package. It builds on the things users love most about Android including easy multitasking, rich notifications, resizable widgets, customizable home screens, and deep interactivity — and adds powerful new ways of communicating and sharing.

We have outlined 10 reasons why Android 4.0 is just better than iOS. Many first time buyers overlook the features offered by Android and just focus on the fact that iPhone is produced by Apple. The following 10 reasons will shed some light on some of the key differentiating features that make Android a better mobile operating system.

1. Better User Interface

Unlike the iPhone OS, Android user interface has been constantly refining and evolving over the years. With Android 4.0, Google has made the user interface much more polished and modern. The main feature of the OS is navigation buttons, these make it easier for the user to navigate around the phone. Unlike the iPhone with only one navigation button (Home Button), Android phones have back, menu, and multitasking buttons, which allow the user to very easily perform these actions whith out having to look for the virtual buttons in an application.

Android utilizes the entire screen with screenshots of the running applicaitons compared to iOS, where multitasking is only done using the dock at the bottom. iOS wastes the entire screen space when it comes to multitasking.
On the iPhone there is only one thing you see, a page full of applications and nothing more. This makes the user interface very boring and dull as the space on your home screen not being used efficiently to provide rich experience for the user. iOS might be easier to use but it is time to move on from an operating system designed for technologically challenged individuals. The Android user interface separates your home screens from the applications list and provides a space that you can customize the way you want. This is the main reason why every single Android phone looks different and unique unlike the iPhone.


2. Resizable Widgets

This feature is exclusive to Android when comparing to the iOS. The home screens in Android 4.0 are designed to be content-rich and customizable allowing the user to embed live application content directly through interactive widgets. Widgets let you check email, flip through a calendar, play music, check social streams, and more — right from the home screen, without having to launch apps. Widgets are resizable, so you can expand them to show more content or shrink them to save space. The retina display on the iPhone is a waste if you use it to display just a grid of icons page after page.
 
3. Swipe to dismiss notifications, tasks, and browser tabs

Android 4.0 makes managing notifications, recent apps, and browser tabs even easier. You can now dismiss individual notifications, apps from the Recent Apps list, and browser tabs with a simple swipe of a finger. This provides a unified experience to the user with quick and easy way to manage the content on your phone.
4. Quick responses for incoming calls

When an incoming call arrives, you can now quickly respond by a text message, without needing to pick up the call or unlock the device. On the incoming call screen, you simply slide a control to see a list of text responses and then tap to send and end the call. You can add your own responses and manage the list from the Settings app. On iOS you can only answer or decline the incoming call, there is no additional functionality that provides the user with more ways to respond.

 
5. Improved text input and spell-checking

The soft keyboard in Android 4.0 makes text input even faster and more accurate. To fix misspelled words more easily, Android 4.0 adds a spell-checker that locates and underlines errors and suggests replacement words. With one tap, you can choose from multiple spelling suggestions, delete a word, or add it to the dictionary. You can even tap to see replacement suggestions for words that are spelled correctly. For specialized features or additional languages, you can now download and install third-party dictionaries, spell-checkers, and other text services.


 6. Powerful voice input engine

Android 4.0 introduces a powerful new voice input engine that offers a continuous “open microphone” experience and streaming voice recognition. This lets you dictate the text you want, for as long as you want, using the language you want. The voice recognition is done in real time allowing you to look at the interpreted text as you speak. You no longer have to finish your speech and wait to see the transcribed text. Siri on iOS provides options to search the web directly but it is used more for entertainment purposes as it is still in beta form. Text-to-speech options on Android are more governed towards productivity allowing you to finish the task easily and effectively.
7. Control over network data

In the Settings app, colorful charts show the total data usage on each network type (mobile or Wi-Fi), as well as amount of data used by each running application. Based on your data plan, you can optionally set warning levels or hard limits on data usage or disable mobile data altogether. You can also manage the background data used by individual applications as needed.
8. Cloud-connected experience

Android has always been cloud-connected, letting you browse the web and sync photos, apps, games, email, and contacts — wherever you are and across all of your devices. Android has always provided superior cloud experience way before Apple introduced their cloud based services. Android users have always enjoyed this feature as you never have to worry about losing your personal information with your phone.

9. Google Experience

If you are a gmail user then Android OS is made just for you and with all of your needs in mind. Android provides the best google experience including GMail, Google Calendar, Google Maps, Google Voice, Google Search, YouTube, Google Goggles, Google Talk, Google Translate, Google Earth, Blogger, and Chrome to Phone. This list provides more than enough reasons for gmail users to own an Android device. Google has also introduced Google Chrome browser which allows you to sync your bookmarks and view tabs you have open on your computer. You can send pages from desktop Chrome to your smartphone or tablet with one click and read them on the go, even if you’re offline. Neither the iPhone nor any other phone on the market will provide immersive and rich google experience the way Android does.



10. Google Maps and FREE voice-guided Navigation

If you use your phone for navigation or destination searches then Google Maps Navigation provides you the best experience on Android 4.0. Google has built in a free voice guided turn-by-turn GPS navigation. The application also provides driving, public transit, biking, and walking directions as well. This is exclusive only to Android as the iOS version of Google Maps provides just the core functionality.

In addition, Google has also included Android Beam for NFC-based sharing and Face Unlock in Android 4.0. Android Beam is an innovative, convenient feature for sharing across two NFC-enabled devices, It lets people instantly exchange favorite apps, contacts, music, videos — almost anything.Face Unlock is a new screen-lock option that lets you unlock your device with your face. It takes advantage of the device front-facing camera and state-of-the-art facial recognition technology to register a face during setup and then to recognize it again when unlocking the device.
In conclusion, many iOS users will argue that some of the features mentioned in this post can be added by jailbreaking or installing third party applications but these features are included in Android by default. Android currently has around 450,000 applications available in Play Store and with its current growth rate it is expected to surpass the App Store in the coming months. Apple’s iOS gets the fluidity and responsiveness at an expense of some key features that are essential for any smartphone. Anyone can achieve fast and responsive UI with a locked down user interface like iOS. The applications, mentioned in this post, are all present on both platforms but Android is the only OS that provides additional functionality that proves to be very essential for its users. Given the aforementioned reasons, Android 4.0 Ice cream sandwich is clearly the superior mobile operating system. With 50.1% of smartphone market in the United States, Android will continue to gain more market share as more and more people discover the amazing features that make Android better than iOS.

Monday, 2 April 2012

Android has more Features

  1. Desktop widgets
  2. Battery removal
  3. External SD card storage up to 32GB
  4. Phone can be used as a flash drive
  5. Multitasking just like your computer (MAC or PC)
  6. Notification system (emails, texts, voicemail, Facebook, calendar and more)
  7. Personalization – Stocks, Hello Kitty, Superman, Bowling, Gucci or whatever.
  8. More free apps. (Essential apps that you pay for on iPhone are free on Android)
  9. Voice everything – text, search and navigation
  10. Carrier choice (basically all carriers carry Android phones)
  11. Video Chat on phones or computers via Gtalk, Skype, Yahoo or almost anything (not just iPhone users with FaceTime – that’s’ just dumb).
  12. Video Chat on 3G, 4G, or WiFi
  13. Phone prices (there are phones that are significantly cheaper than the iPhone.
  14. Manufacturer choices (ex. if you want your Samsung TV to work with Samsung phone, it can).
  15. Size choices (if you like a huge phone or small phone you can choose).
  16. Keyboard or Virtual Keyboard
  17. Talking GPS based on Google Maps with Satellite and 3D views.
  18. Standard cheap easy micro USB charging, use your old Blackberry charger.
  19. Editable dictionary
  20. Fantastic Google Voice integration
  21. Download all types of music (from iTunes or anywhere else)
  22. Portable WiFi Hotspot
  23. Tethering without jail breaking or rooting the Phone
  24. Sync calendar and contact information for free over the air
  25. Develop your own customized apps for free.
  26. Better rear and front camera choices
  27. Over the air music syncing and streaming
  28. Seeing all websites even ones with Flash
  29. Install any app you want even competitor apps
  30. Constant updates so the need to get a new phone is almost obsolete.

Rounded or Circle ImageView with Shadow in Android

RoundedImageViewShadow.java public class RoundedImageViewShadow extends ImageView {     private static final ScaleType SCALE_TYPE ...