Pages

Tuesday 22 December 2015

Android Mime Type File manager

In Following link have working example of Mime Type File manager.

It will display photo,video or audio from external attached device. in case if it's not working than remove sd-card and re-insert it. then try. or try with phone restart.

Demo :
https://sites.google.com/site/fancifulandroid/android-projects/USB-connection%28FileManager%29.zip?attredirects=0&d=1

Android get mime type of file or url

Use following function to get MIME Type of file. pass file path or any url

public static String getMimeType(String url) {
  try {
   String type = null;
   String extension = url.substring(url.lastIndexOf(".") + 1, url.length());
   Log.i("extension", "ext : " + extension);
   if (extension != null) {
    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
   }
   return type;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
}

Thursday 22 October 2015

Android sql prepared statements, how to prevent sql injection

Generally do not use query directly as string.
Android have default classes so we can use those function to prevent sql injection.

For ex,

To get records from db and suppose you have joins or sub query so default 'query' may no use in such case we will use following funcitons.

String sql = "select *,(select type from table 2 where table2.type=? limit 1) as type from table1 where table1.name like ?";

DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();

Cursor c = sqLiteDatabase.rawQuery(sql, new String[]{"car","m%"});


If we have "IN" clause in sql statement then we may use it following way.

String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
    + " WHERE name IN (" + TextUtils.join(",", Collections.nCopies(names.length, "?"))  + ")";
Cursor cursor = mDb.rawQuery(query, names); 


For insert,update and delete we may use default following functions

insert (String table, String nullColumnHack, ContentValues values) ;

update (String table, ContentValues values, String whereClause, String[] whereArgs); 

delete(String table, String whereClause, String[] whereArgs)

query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) // we may use it for simple SELECT query

Monday 12 October 2015

Android play video programmatically

Use following code to play video.

vvVideo = (VideoView) findViewById(R.id.vvVideo);
// use this to play video from raw resource
  vvVideo.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.main));
// use this to play video from url (streaming)
  vvVideo.setVideoURI(Uri.parse("http://..."));
// if possible do not use height to match_parent. It may create problem. I am not sure about this.
// play video from asset
  vvVideo.setVideoURI(Uri.parse("file:///android_asset/path/to/your.mp4"));
// play video from sdcard
  vvVideo.setVideoURI(Uri.fromFile(new File("/sdcard/cats.jpg")));


  vvVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
   @Override
   public void onCompletion(MediaPlayer mp) {
    // video play complete
   }
  });

  vvVideo.start();

use following xml

<VideoView
        android:id="@+id/vvVideo"
        android:layout_width="match_parent"
        android:layout_height="488dp"
        android:layout_centerInParent="true"
        />

add read external storage permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

Monday 5 October 2015

Android add contact intent with save and cancel action

Use following code to open Add contact screen.

Intent i = new Intent(Intent.ACTION_INSERT);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (Integer.valueOf(Build.VERSION.SDK_INT) > 14)
 i.putExtra("finishActivityOnSaveCompleted", true); // Fix for 4.0.3 +
startActivityForResult(i, ADD_CONTACT_REQUEST);

in On activityResult we will get added contact URI .

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == ADD_CONTACT_REQUEST) {

   if (resultCode == RESULT_OK) {
    Log.i("contact ", "Added successfully");
    Log.i("data", data.toString() + ",   uri : " + data.getData().toString());
   } else {
    Log.i("contact ", "contact add cancelled ");
   }
  }
 }

Saturday 3 October 2015

How to generate push notification using compat v7 and manage backstack

Benefit : we no need to worry about android's version. It will automatically handle version relevant changes.

Following code to generate push-notification


public Notification notification;
public NotificationCompat.Builder notificationBuilder;

PendingIntent pIntent;
String message;
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("from_notification", true);
pIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap image = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
notificationBuilder = new NotificationCompat.Builder(context)
      .setContentTitle(context.getString(R.string.app_name))
      .setTicker(message)
      .setContentText(message)
      .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
      .setSmallIcon(R.mipmap.icon)
      .setLargeIcon(image)
      .setColor(context.getResources().getColor(R.color.white))
      .setContentIntent(pIntent)
      .setAutoCancel(true);

notification = notificationBuilder.build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(id, notification);

Note : if you want to update notification just use notificationBuilder.

notificationBuilder
      .setTicker(message)
      .setContentText(message)
      .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
      .setContentIntent(pIntent)
      .setNumber(totalMessages);
notification = notificationBuilder.build();
notificationManager.notify(id, notification);

id must be same as time of creation.


Manage backstack from push-notification :
For example you are developing chat app.
Suppose You got message from friend as push-notification. And assume that app is not running. Now if you click on notification it will redirect to chat-detail screen. And if you click back button it should go back to Friend list instead of close app . For this we need to manage task backstack using following code.

1) Suppose ChatMessageActivity is child activity and ChatActivity is parent activity. So by click on push we will open ChatMessageActivity and press back we will redirect to ChatActivity. Add parent and child activity in manifest file.


<activity
    android:name=".ChatActivity"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
<!-- Add child activity -->
<activity
    android:name=".ChatMessageActivity"
    android:launchMode="singleTask"
    android:parentActivityName=".ChatActivity"
    android:screenOrientation="portrait">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.app.ChatActivity"/>
</activity>

1) Create object of TaskStackBuilder.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
 
2) Adds the back stack
stackBuilder.addParentStack(ChatMessageActivity.class);
 
3) Adds the Intent to the top of the stack
stackBuilder.addNextIntent(intent); // Here intent is point to activity which we want to open
 
4) get pending intent from stack builder and use that in above code.
pIntent = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);

Thursday 1 October 2015

Set TextView style (bold or italic) programmatically

use following code to change style

textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);


change null to textView.getTypeface() to preserve current typeface

Android date and time formate

Following is example of date and time formate from timeMillis.

Date date = new Date(time millis here);
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a");
String receivedTime = formatter.format(date); // hh:mm a format
// it may return like 06:55 PM

SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy");
String receivedDate = dateformatter .format(date);
// it may return like 22-09-2015 


Following link have more format char.
http://developer.android.com/reference/java/text/SimpleDateFormat.html

How do I make links in a TextView clickable?

I'm using only android:autoLink="web" and it works fine. A click on the link opens the browser and shows the correct page.

How to Copy Text to Clip Board in Android?

Use this class to copy text to clipboard

package com.dedoc.app.utils;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by hb on 01-Oct-15.
 */
public class MyClipboardManager {

 @SuppressLint("NewApi")
 @SuppressWarnings("deprecation")
 public static boolean copyToClipboard(Context context, String text) {
  try {
   int sdk = android.os.Build.VERSION.SDK_INT;
   if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
      .getSystemService(context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
   } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
      .getSystemService(context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData
      .newPlainText("", text);
    clipboard.setPrimaryClip(clip);
   }
   return true;
  } catch (Exception e) {
   return false;
  }
 }

 @SuppressLint("NewApi")
 public static  String readFromClipboard(Context context) {
  int sdk = android.os.Build.VERSION.SDK_INT;
  if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
   android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
     .getSystemService(context.CLIPBOARD_SERVICE);
   return clipboard.getText().toString();
  } else {
   ClipboardManager clipboard = (ClipboardManager) context
     .getSystemService(Context.CLIPBOARD_SERVICE);

   // Gets a content resolver instance
   ContentResolver cr = context.getContentResolver();

   // Gets the clipboard data from the clipboard
   ClipData clip = clipboard.getPrimaryClip();
   if (clip != null) {

    String text = null;
    String title = null;

    // Gets the first item from the clipboard data
    ClipData.Item item = clip.getItemAt(0);

    // Tries to get the item's contents as a URI pointing to a note
    Uri uri = item.getUri();

    // If the contents of the clipboard wasn't a reference to a
    // note, then
    // this converts whatever it is to text.
    if (text == null) {
     text = coerceToText(context, item).toString();
    }

    return text;
   }
  }
  return "";
 }

 @SuppressLint("NewApi")
 public static CharSequence coerceToText(Context context, ClipData.Item item) {
  // If this Item has an explicit textual value, simply return that.
  CharSequence text = item.getText();
  if (text != null) {
   return text;
  }

  // If this Item has a URI value, try using that.
  Uri uri = item.getUri();
  if (uri != null) {

   // First see if the URI can be opened as a plain text stream
   // (of any sub-type). If so, this is the best textual
   // representation for it.
   FileInputStream stream = null;
   try {
    // Ask for a stream of the desired type.
    AssetFileDescriptor descr = context.getContentResolver()
      .openTypedAssetFileDescriptor(uri, "text/*", null);
    stream = descr.createInputStream();
    InputStreamReader reader = new InputStreamReader(stream,
      "UTF-8");

    // Got it... copy the stream into a local string and return it.
    StringBuilder builder = new StringBuilder(128);
    char[] buffer = new char[8192];
    int len;
    while ((len = reader.read(buffer)) > 0) {
     builder.append(buffer, 0, len);
    }
    return builder.toString();

   } catch (FileNotFoundException e) {
    // Unable to open content URI as text... not really an
    // error, just something to ignore.

   } catch (IOException e) {
    // Something bad has happened.
    Log.w("ClippedData", "Failure loading text", e);
    return e.toString();

   } finally {
    if (stream != null) {
     try {
      stream.close();
     } catch (IOException e) {
     }
    }
   }

   // If we couldn't open the URI as a stream, then the URI itself
   // probably serves fairly well as a textual representation.
   return uri.toString();
  }

  // Finally, if all we have is an Intent, then we can just turn that
  // into text. Not the most user-friendly thing, but it's something.
  Intent intent = item.getIntent();
  if (intent != null) {
   return intent.toUri(Intent.URI_INTENT_SCHEME);
  }

  // Shouldn't get here, but just in case...
  return "";
 }

}

Saturday 8 August 2015

android multiple listView or multiple expandable listView in one screen

To make whole screen scrollable when screen having more then one listview or more then one ExpandableListView.

First we need to measure height of whole list and apply same height to that list. we need to calculate height for all list separately.

Following code will use to calculate height of Expandable list

public static boolean setListViewHeightBasedOnItems(ExpandableListView listView) {

  ExpandableJunkListAdapter listAdapter = (ExpandableJunkListAdapter) listView.getExpandableListAdapter();
  if (listAdapter != null) {
   int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
   int numberOfItems = listAdapter.getGroupCount();

   // Get total height of all items.
   int totalItemsHeight = 0;
   for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
    View item = listAdapter.getGroupView(itemPos, listView.isGroupExpanded(itemPos), null, listView);
    View childItem = null;
    int noOfChilds = listAdapter.getRealChildrenCount(itemPos);
    int childPos = 0;
    if (listView.isGroupExpanded(itemPos)) {

     for (childPos = 0; childPos < noOfChilds; childPos++) {
      if (childPos == (noOfChilds - 1)) {
       childItem = listAdapter.getRealChildView(itemPos, childPos, true, null, listView);
      } else {
       childItem = listAdapter.getRealChildView(itemPos, childPos, false, null, listView);
      }
      childItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
      totalItemsHeight += childItem.getMeasuredHeight();
     }
    }
    item.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
    totalItemsHeight += item.getMeasuredHeight();
   }

   // Get total height of all item dividers.
   int totalDividersHeight = listView.getDividerHeight() * (numberOfItems - 1);

   // Set list height.
   ViewGroup.LayoutParams params = listView.getLayoutParams();
   params.height = totalItemsHeight + totalDividersHeight;
   // Log.i("height", "" + params.height);
   Log.e("height", "" + params.height);
   listView.setLayoutParams(params);
   listView.requestLayout();

   return true;

  } else {
   return false;
  }
 }

you need to call this function at the time of "setAdapter","notifydatasetChanged", "ongroupClick" for expandableListView.  
Whenever any view related operation performed then we need to call this function to calculate actual height of list.

For ListView We may use following function. call it at time of Notifydatasetchaged, setAdapter etc

public static void getTotalHeightofListView(ListView listView) {

    ListAdapter mAdapter = listView.getAdapter();

    int totalHeight = 0;

    for (int i = 0; i < mAdapter.getCount(); i++) {
        View mView = mAdapter.getView(i, null, listView);

        mView.measure(
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),

                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

        totalHeight += mView.getMeasuredHeight();
        Log.w("HEIGHT" + i, String.valueOf(totalHeight));

    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();

}

Tuesday 4 August 2015

Tuesday 28 April 2015

Uninstall android studio from mac

Execute these commands from the terminal in mac
rm -Rf /Applications/Android\ Studio.app
rm -Rf ~/Library/Caches/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Preferences/AndroidStudio*
rm ~/Library/Preferences/com.google.android.studio.plist
rm -Rf ~/Library/Application\ Support/AndroidStudio*

Extra commands. please read carefully before execute following
if you would like to delete all projects:
rm -Rf ~/AndroidStudioProjects
to remove gradle related files (caches & wrapper)
rm -Rf ~/.gradle
use the below command to delete all Android Virtual Devices(AVDs) and *.keystore. note: this folder is used by others Android IDE as well, so if you still using other IDE you may not want to delete this folder)
rm -Rf ~/.android
to delete Android SDK tools

rm -Rf ~/Library/Android*

Monday 27 April 2015

Same-named attributes in attrs.xml for custom view

Simply extract common attributes from both views and add them directly as children of the <resources>  node:
For Example

<resources>
    <attr format="string" name="myattr1">
    <attr format="integer" name="myattr2">

    <declare-styleable name="customView1">
        <attr name="myattr1">
        <attr name="myattr2">
        ...
    </attr></attr></declare-styleable>

    <declare-styleable name="customView2">
        <attr name="myattr1">
        <attr name="myattr2">
        ...
    </attr></attr></declare-styleable>

<!-- if want to use one attar -->
 <declare-styleable name="customView3">
        <attr name="myattr1">
      
        ...
    </attr></declare-styleable>
</attr></attr></resources>

Saturday 18 April 2015

Android get image, audio , video file list quickly

Android have inbuilt functions to retrive list.

Following is demo for Image list. for audio , video and even for other types of file you can use similar functions.

/**
* Used to get images from whole phone
*/
public void get_all_image_folders() {
// which image properties are we querying

String[] projection = new String[] { MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
 };

Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

// Make the query.

String sortOrder = MediaStore.Images.Media.DATE_TAKEN + " Desc";

Cursor cur = getContentResolver().query(images, projectionnull,null, sortOrder);
if (cur.moveToFirst()) {
String bucket;
String date;
int bucketColumn = cur
.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

int dateColumn = cur
.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);


do {
// Get the field values
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);

// Do something with the values.
Log.i("ListingImages", " bucket=" + bucket + "  date_taken="
+ date + "" );
} while (cur.moveToNext());

}

}

How to get size of all mounted or unmounted devices

StorageUtils class to find storage card info


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;

import android.os.Environment;
import android.util.Log;

public class StorageUtils {

private static final String TAG = "StorageUtils";

public static class StorageInfo {

public final String path;
public final boolean readonly;
public final boolean removable;
public final int number;

StorageInfo(String path, boolean readonly, boolean removable, int number) {
this.path = path;
this.readonly = readonly;
this.removable = removable;
this.number = number;
}

public String getDisplayName() {
StringBuilder res = new StringBuilder();
if (!removable) {
res.append("Internal SD card");
} else if (number > 1) {
res.append("SD card " + number);
} else {
res.append("SD card");
}
if (readonly) {
res.append(" (Read only)");
}
return res.toString();
}
}

public static List<StorageInfo> getStorageList() {

List<StorageInfo> list = new ArrayList<StorageInfo>();
String def_path = Environment.getExternalStorageDirectory().getPath();
boolean def_path_removable = Environment.isExternalStorageRemovable();
String def_path_state = Environment.getExternalStorageState();
boolean def_path_available = def_path_state
.equals(Environment.MEDIA_MOUNTED)
|| def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
boolean def_path_readonly = Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED_READ_ONLY);

HashSet<String> paths = new HashSet<String>();
int cur_removable_number = 1;

if (def_path_available) {
paths.add(def_path);
list.add(0, new StorageInfo(def_path, def_path_readonly,
def_path_removable,
def_path_removable ? cur_removable_number++ : -1));
}

BufferedReader buf_reader = null;
try {
buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
String line;
Log.d(TAG, "/proc/mounts");
while ((line = buf_reader.readLine()) != null) {
Log.d(TAG, line);
if (line.contains("vfat") || line.contains("/mnt")
|| line.contains("/sdcard")) {
StringTokenizer tokens = new StringTokenizer(line, " ");
String unused = tokens.nextToken(); // device
String mount_point = tokens.nextToken(); // mount point
if (paths.contains(mount_point)) {
continue;
}
unused = tokens.nextToken(); // file system
List<String> flags = Arrays.asList(tokens.nextToken()
.split(",")); // flags
boolean readonly = flags.contains("ro");

if (line.contains("/dev/block/vold") || line.contains("/dev/fuse")) {
if (!line.contains("/mnt/secure")
&& !line.contains("/mnt/asec")
&& !line.contains("/mnt/obb")
&& !line.contains("/dev/mapper")
&& !line.contains("tmpfs")) {
paths.add(mount_point);
list.add(new StorageInfo(mount_point, readonly,
true, cur_removable_number++));
}
}
}
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (buf_reader != null) {
try {
buf_reader.close();
} catch (IOException ex) {
}
}
}
return list;
}



}

----------------------------------------
In activity add following code.

private float[] getMemInfo(String path) {
StatFs statFs = new StatFs(path);
long blockSize = statFs.getBlockSize();
float totalSize = statFs.getBlockCount() * blockSize
/ (1024f * 1024f * 1024f);
float availableSize = statFs.getAvailableBlocks() * blockSize
/ (1024f * 1024f * 1024f);
float freeSize = statFs.getFreeBlocks() * blockSize
/ (1024f * 1024f * 1024f);

return new float[] { totalSize, availableSize, freeSize };

}

Print sd-card detail using following code
// sd card data

String storage = "";
List<StorageInfo> mList = StorageUtils.getStorageList();
for (int i = 0; i < mList.size(); i++) {
try {
StorageInfo mStorageInfo = mList.get(i);
float[] mInfo = getMemInfo(mStorageInfo.path);

storage += "\n External " + mStorageInfo.number + " : total = "
+ String.format("%.2f GB", mInfo[0])
+ " , available = "
+ String.format("%.2f GB", mInfo[1]);
} catch (Exception e) {
e.printStackTrace();
}

}
---------------------------
get RAM information

/**
* RAM related functions
*/

private int getFreeRamPercentage() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
double raminfo[] = getTotalRAM();
int percentAvail = -1;
if (raminfo[0] != 0) {
percentAvail = (int) (mi.availMem * 100 / raminfo[0]);
}

return percentAvail;

}

public double[] getTotalRAM() {

RandomAccessFile reader = null;
String load = null;
DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
double raminfo[] = new double[2];
String lastValue = "";
try {
reader = new RandomAccessFile("/proc/meminfo", "r");
load = reader.readLine();
Log.i("ram-info", load);
String total = parseInfoFromCommand(load);

load = reader.readLine();
Log.i("freee-ram-info", load);
String free = parseInfoFromCommand(load);

reader.close();

raminfo[0] = Double.parseDouble(total) * 1024;
raminfo[1] = Double.parseDouble(free) * 1024;
return raminfo;

} catch (IOException ex) {
ex.printStackTrace();
} finally {
}

return raminfo;
}

private String parseInfoFromCommand(String load) {
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(load);
String value = "";
while (m.find()) {
value = m.group(1);
}
return value;

}

Tuesday 14 April 2015

android list view row animation reference links

This is nice library.

just did minor changes in adapter like set duration etc and animation will work .
There are many animations like fade in ,fade out , wave, shake and many more.

https://github.com/karnshah8890/tech_andy/tree/master/ListviewAnimationDemo

Wednesday 11 February 2015

Android animation must know points

This is specially for objection Animator.

- if you have such requirement that in animation one view visibility change to visible and same time other view's gone (For example view flipper) then set default (before animation start) visibility after animation start.

-sometimes I phase following problem . In animator xml if there is rotation and alpha. In xml if I wrote code for rotation and then alpha then alpha is not affecting even if  I have set no offset in alpha.

For ex :

Alpha Not working

 <!-- Rotate. -->
    <objectAnimator
        android:duration="@integer/card_flip_time_half"
        android:interpolator="@android:interpolator/linear"
        android:propertyName="rotationY"
        android:valueFrom="0"
        android:valueTo="90"
        android:startOffset="@integer/resize_time_delay" />

<objectAnimator
        android:duration="0"
        android:propertyName="alpha"
        android:valueFrom="0.0"
        android:valueTo="1.0"
         />


Alpha working


<objectAnimator
        android:duration="0"
        android:propertyName="alpha"
        android:valueFrom="0.0"
        android:valueTo="1.0"
         />

 <!-- Rotate. -->
    <objectAnimator
        android:duration="@integer/card_flip_time_half"
        android:interpolator="@android:interpolator/linear"
        android:propertyName="rotationY"
        android:valueFrom="0"
        android:valueTo="90"
        android:startOffset="@integer/resize_time_delay" />