Saturday 15 November 2014

Books ShelfView in Android

Hello Friends,

Today I am going to show you that how you can create Book Shelf View in android. I research soo many and finally i reached to one best and simple way to create shelf View in Android.

In this example i have implemented the Custom Shelf View which will create a shelf. The list of the books will come in the form of JSON response and by parsing it show the details of books in shelfview along with its thumbnails. I wrote a class that extends AdapterView to create a customized GridView that I called "shelf view".



Below is the code of ShelView:

BookShelfView.java

 public class BookshelfView extends GridView {  
  private Bitmap background;  
  public BookshelfView(Context context) {  
  super(context);  
  init();  
  }  
  public BookshelfView(Context context, AttributeSet attrs) {  
  super(context, attrs);  
  init();  
  }  
  public BookshelfView(Context context, AttributeSet attrs, int defStyle) {  
  super(context, attrs, defStyle);  
  init();  
  }  
  protected void init() {  
  //Set the background image of the ShelfView panel.  
  background = BitmapFactory.decodeResource(getResources(), R.drawable.shelf_panel_new);  
  }  
  //Draw a background in the screen and create multiple panels using height & width.  
  @Override  
  protected void dispatchDraw(Canvas canvas) {  
  int top = getChildCount() > 0 ? getChildAt(0).getTop() : 0;  
  for (int y = top; y < getHeight(); y += background.getHeight()) {  
   for (int x = 0; x < getWidth(); x += background.getWidth()) {  
   canvas.drawBitmap(background, x, y, null);  
   }  
  }  
  super.dispatchDraw(canvas);  
  }  
 }  





Wednesday 6 August 2014

ANDROID DESIGN CHEATSHEET

Android cheatsheet for graphic designers

Android cheatsheet for graphic designers

Graphic designers aren't programmers and sometimes don't know how to properly prepare graphic assets for developers. This simple cheatsheet should help them to do their job better, and to simplify developers' lives.

Content

  1. Dimensions
    1. Screen densities and icon dimensions
    2. Google Play asset dimensions
    3. Dimension units
    4. Size buckets
    5. Views dimensions and spacing
    6. Action bar height
    7. Text size
  2. Images and themes
    1. Nine-patch
    2. Colors
    3. Holo themes
  3. Naming conventions
    1. Naming conventions for drawables
    2. Naming conventions for icon assets
    3. Naming conventions for selector states
    4. Organizing drawables to directories
  4. Resources
    1. Graphic generators
    2. Useful links for designers
    3. Download
  5. Written by

Dimensions

Screen densities and icon dimensions

Qualifier DPI Scaling factor Launcher icon Action bar, tab icon Notification icon (API 11) Notification icon (API 9) Notification icon (older)
ldpi 120 0.75 36 x 36
32 x 32
24 x 24
18 x 18
18 x 18
16 x 16
12 x 19
12 x 12
19 x 19
16 x 16
mdpi 160 1.0 48 x 48
42 x 42
32 x 32
24 x 24
24 x 24
22 x 22
16 x 25
16 x 16
25 x 25
21 x 21
hdpi 240 1.5 72 x 72
64 x 64
48 x 48
36 x 36
36 x 36
33 x 33
24 x 38
24 x 24
38 x 38
32 x 32
xhdpi 320 2.0 96 x 96
84 x 84
64 x 64
48 x 48
48 x 48
44 x 44
32 x 50
32 x 32
50 x 50
42 x 42
xxhdpi 480 3.0 144 x 144
126 x 126
96 x 96
72 x 72
72 x 72
66 x 66
48 x 75
48 x 48
75 x 75
63 x 63

Notice: the first icon dimension in table cell is full asset size, the second icon dimension is optical square. Dimension values are in pixels.

Tip: creating ldpi assets is not really needed anymore. The devices are rare and the platform will just scale down mdpi.

Sources and useful links: Iconography, Supporting Multiple Screens, Icon Design Guidelines, Dimension

Google Play asset dimensions

Asset Type Required Image type Dimension
Screenshot yes JPEG or 24-bit PNG
(no alpha)
min length for any side: 320 px
max length for any side: 3840 px
High-res app icon yes 32-bit PNG
(with alpha)
512 x 512 px
Feature graphic no JPEG or 24-bit PNG
(no alpha)
1024 x 500 px
Promotional graphic no JPEG or 24-bit PNG
(no alpha)
180 x 120 px
Video link no URL of YouTube video -

Sources and useful links: Graphic and Image Assets, Google Play Featured-Image Guidelines, Iconography

Dimension units

Unit Units / physical inch Density independent Same physical size on every screen
px varies no no
in 1 yes yes
mm 25.4 yes yes
pt 72 yes yes
dp ~160 yes no
sp ~160 yes no

Sources and useful links: Understanding Density Independence in Android

Size buckets

Type Dimension
Handset smaller than 600 dp
Tablet larger than or equal 600 dp

Size buckets

Notice: one dp (density-independent pixel) is one pixel on a 160 DPI screen.

Sources and useful links: Metrics and Grids

Views dimensions and spacing

Touchable UI components are generally laid out along 48 dp units. Spacing between each UI element is 8 dp.

48dp rhythm

Button dimensions and spacing

Form dimensions and spacing

Sources and useful links: Metrics and Grids

Action bar height

Qualifier Dimension
Portrait 48 dp
Landscape 40 dp
Tablet 56 dp

Sources and useful links: Action Bar

Text size

Type Dimension
Micro 12 sp
Small 14 sp
Medium 18 sp
Large 22 sp

Notice: one sp (scale-independent pixel) is one pixel on a 160 DPI screen if the user's global text scale is set to 100%.

Sources and useful links: Typography

Images and themes

Nine-patch

A Nine-patch drawable is a stretchable bitmap image, which Android will automatically resize to accommodate the contents of the view in which you have placed it as the background, e.g. nine-patch background for button, which must stretch to accommodate strings of various lengths. The rules for nine-patch image are following:

  • Standard PNG image with alpha
  • Filename suffix is ".9.png", e.g. "btn_login_normal.9.png"
  • Image has an extra 1 pixel wide border, used to define the stretchable/static/padding areas
  • Stretchable sections are indicated by 1 px wide black line(s) in the left and top part of the border
  • Static sections are indicated by fully transparent or white pixels
  • Padding area (optional) is indicated by 1 px wide black line in the right and bottom part of the border

Nine-patch

Sources and useful links: Canvas and Drawables, Draw 9-patch, Simple Nine-patch Generator

Colors

Use color primarily for emphasis. Blue is the standard accent color in Android's color palette. Note that red and green may be indistinguishable to color-blind users. Primary colors are as follows:

  • #33B5E5
  • #AA66CC
  • #99CC00
  • #FFBB33
  • #FF4444
  • #0099CC
  • #9933CC
  • #669900
  • #FF8800
  • #CC0000

Sources and useful links: Color

Holo themes

Android provides three system themes:

  • Holo Light
  • Holo Dark
  • Holo Light with dark action bar

Sources and useful links: Themes, Holo Everywhere

Naming conventions

Naming conventions for drawables

File names must contain only lowercase a-z, 0-9, or _.

Drawables for the specific views (ListView, TextView, EditText, ProgressBar, CheckBox etc.) should be named like this views keeping the naming rules, e.g. drawable for CheckBox should be named "checkbox_on_bg.png".

Asset Type Prefix Example
Action bar ab_ ab_stacked.9.png
Button btn_ btn_send_pressed.9.png
Dialog dialog_ dialog_top.9.png
Divider divider_ divider_horizontal.9.png
Icon ic_ ic_star.png
Menu menu_ menu_submenu_bg.9.png
Notification notification_ notification_bg.9.png
Tabs tab_ tab_pressed.9.png

Sources and useful links: naming conventions taken from the Android SDK

Naming conventions for icon assets

Asset Type Prefix Example
Icons ic_ ic_star.png
Launcher icons ic_launcher ic_launcher_calendar.png
Action bar icons ic_menu ic_menu_archive.png
Status bar icons ic_stat_notify ic_stat_notify_msg.png
Tab icons ic_tab ic_tab_recent.png
Dialog icons ic_dialog ic_dialog_info.png

Sources and useful links: Icon Design Guidelines

Naming conventions for selector states

State Suffix Example
Normal _normal btn_order_normal.9.png
Pressed _pressed btn_order_pressed.9.png
Focused _focused btn_order_focused.9.png
Disabled _disabled btn_order_disabled.9.png
Selected _selected btn_order_selected.9.png

Sources and useful links: Touch Feedback

Organizing drawables to directories

One drawable must have the same file name for all screen densities (ldpi, mdpi, hdpi etc.) and all these files must be organized according to density into the following directories. Here's the resources directory structure for drawables:

  • res
    • drawable-ldpi
    • drawable-mdpi
    • drawable-hdpi
    • drawable-xhdpi
    • drawable-xxhdpi

Resources

Graphic generators

Download

Android Icon Templates Pack v4.0
Source: Android Developers

Android Design 11/2013
Source: Android Developers

Android UI Design Kit PSD 4.4
Source: Taylor Ling on Android UI & UX

Android Developer Icons – Photoshop Shapes
Source: Spiderfly Apps

Sunday 13 July 2014

Get Latitude & Longitude from Address in Android

Below is the simple code to get the Latitude & Longitude from the zip code of  city.

 private Geocoder geocode = new Geocoder(this);  
 String address = "<zip code>";  
 /**  
 * Method to get latitude,longitude from address.  
 * @param addressStr-Address or zip code of city.  
 * @param gc- Geocoder instance.  
 *   
 */  
 public static void geocodeAddress(String addressStr, Geocoder gc) {  
     Address address = null;  
     List<Address> addressList = null;  
    try {  
       if (!TextUtils.isEmpty(addressStr)) {  
        addressList = gc.getFromLocationName(addressStr, 5);  
      }  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
    if (null != addressList && addressList.size() > 0) {  
           address = addressList.get(0);  
     }  
    if (null != address && address.hasLatitude()  
     && address.hasLongitude()) {  
           latitude = address.getLatitude();  
           longitude = address.getLongitude();  
       }  
    if (latitude != null && longitude != null)  
     {  
     mGoogleMap2.addMarker(new MarkerOptions()  
        .position(new LatLng(latitude, longitude)));  
    mGoogleMap2.moveCamera(CameraUpdateFactory.newLatLngZoom(  
       new LatLng(latitude, longitude), 10));  
     }  
  }  

Managing Bottom key like HOME,MENU,BACK keys in Android

Hello Friends,

                  Once again I am back with the article which will guide for managing android device's Basic keys i.e. HOME,MENU,BACK,SETTINGS,SEARCH keys which comes common in most of the devices. And sometimes its needed to manage this buttons click events in our application.

There are various Android Application where we need to control the android bottom key panel. This bottom key panel is organised by five keys

1. Back
2. Menu
3. Home
4. Search
5. Settings

If we take any example like online payment Application then we can’t allow a user to press the back button in the middle of payment. So we have to override the back press event and managed the click event.

There are many cases where we provide certain action of the application like action bar menu will be appeared when menu button user will pressed.
This key panel button events are identified by android in following ways
1. Back – KEYCODE_BACK
2. Menu -KEYCODE_MENU
3. Home – KEYCODE_HOME
4. Search – KEYCODE_SEARCH
5. Settings – KEYCODE_SETTINGS
For handling this keys we need to override this method of the Activity
 @Override  
 public boolean onKeyDown(int keyCode, KeyEvent event) {  
 if (keyCode == KeyEvent.KEYCODE_BACK) {  
 //Do Code Here  
 // If want to block just return false  
 return false;  
 }  
 if (keyCode == KeyEvent.KEYCODE_MENU) {  
 //Do Code Here  
 // If want to block just return false  
 return false;  
 }  
 if (keyCode == KeyEvent.KEYCODE_HOME) {  
 //Do Code Here  
 // If want to block just return false  
 return false;  
 }  
 if (keyCode == KeyEvent.KEYCODE_SEARCH) {  
 //Do Code Here  
 // If want to block just return false  
 return false;  
 }  
 if (keyCode == KeyEvent.KEYCODE_SETTINGS) {  
 //Do Code Here  
 // If want to block just return false  
 return false;  
 }  
 return super.onKeyDown(keyCode, event);  
 }  

From Android 4.0 (ICS) onward KEYCODE_HOME has been deprecated. As Android believed that it is wrong to give all the option blocked for user. User can pressed the Home button to navigate to other application. But android keep the current application as it is state in the background. So that user can back to the previous application.
Below i am showing code to manage HOME_KEY in android.
 public class DisableHardButton extends Activity {  
  TextView mTextView;  
  ToggleButton mToggleButton;  
  boolean isLock=false;  
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.main);  
  mTextView=(TextView) findViewById(R.id.tvInfo);  
  mToggleButton=(ToggleButton) findViewById(R.id.btnLock);  
  mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
   @Override  
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  
   isLock=isChecked;  
   onAttachedToWindow();  
   }  
  });  
  }  
  @Override  
  public boolean dispatchKeyEvent(KeyEvent event) {  
  if ( (event.getKeyCode() == KeyEvent.KEYCODE_HOME) && isLock) {  
   mTextView.setText("KEYCODE_HOME");  
   return true;  
  } else {  
   return super.dispatchKeyEvent(event);  
  }  
  }  
  @Override  
  public boolean onKeyDown(int keyCode, KeyEvent event) {  
  if( (keyCode==KeyEvent.KEYCODE_BACK) && isLock) {  
   mTextView.setText("KEYCODE_BACK");  
   return true;  
  }else {  
   return super.onKeyDown(keyCode, event);  
  }  
  }  
  @Override  
  public void onAttachedToWindow() {   
  System.out.println("Onactivity attached :"+isLock);  
  if(isLock) {    
   this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);     
   super.onAttachedToWindow();  
  }else {  
   this.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION);     
   super.onAttachedToWindow();  
  }  
  }  
 }  

This is layout file main.xml 
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   android:orientation="vertical" >  
   <TextView  
     android:id="@+id/tvInfo"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="Hi! This is the testing of override home button" />  
   <ToggleButton  
     android:id="@+id/btnLock"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:textOff="UnLocked"  
     android:textOn="Locked" />  
 </LinearLayout>  

There are another instance user can accidentally press back button and exit the application. In that case we have to give alert to the user before quit the application. For that we need to identify for the last activity in the stack. For that we need to identify and checked for the last activity form the stack.
 private boolean isLastActivity() {  
     final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
     final List tasksInfo = am.getRunningTasks(1024);  
     final String ourAppPackageName = getPackageName();  
     RunningTaskInfo taskInfo;  
    final int size = tasksInfo.size();  
     for (int i = 0; i < size; i++) {  
        taskInfo = tasksInfo.get(i);  
      if (ourAppPackageName  
 .equals(taskInfo.baseActivity.getPackageName())) {  
     return taskInfo.numActivities == 1;  
     }  
    }  
   return false;  
 }  

This way we can manage the android key events 

Tuesday 15 April 2014

FingerTouch Drawing Signature with different colors in Android

Hello Friends,

Today i am going to show you the tutorial of drawing or creating your own signature or simply draw/paint a line using finger with different colors and save it as image. You will be able to draw,clear,save your signature in this tutorial. You will be able to draw a picture as well.


Here i am going to show you the steps to create finger touch view.

Step 1: Create Custom View

The first thing we need to do is to create CustomView by creating a class and extends View in it.

 import android.content.Context;  
 import android.util.AttributeSet;  
 import android.view.View;  
 public class Signature extends View {  
     public Signature(Context context, AttributeSet attrs)  
       {   
          super(context, attrs);    
       }   
    }  

This view you can add in your Activity or you can create separate class called Signature . You can add it inside of a layout and, if you wish to expand on this example, you could add some buttons for colors, etc…
 <com.example.signaturedemo.DrawingView  
     android:id="@+id/drawing"  
     android:layout_width="fill_parent"  
     android:layout_height="0dp"  
     android:layout_marginBottom="3dp"  
     android:layout_marginLeft="5dp"  
     android:layout_marginRight="5dp"  
     android:layout_marginTop="3dp"  
     android:layout_weight="1"  
     android:background="#FFFFFFFF" />  

Now, if we run this, our application will run the activity and create the layout with our custom view.

But this is not enough we need to write the code for drawing line on it. So, lets see the code.


Step 2: Using the onTouch event to draw on a canvas

We need to:
  • Set a paint style
  • Listen for a touch event
  • Create a new starting point when we touch the screen
  • Draw a path when we move our finger
  • Redraw the view when the onTouchEvent fires.
So, lets write the code as below:
 public class Signature extends View {  
  private static final float STROKE_WIDTH = 5f;  
  private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;  
  private Path m_path = new Path();  
  private float m_lastTouchX;  
  private float m_lastTouchY;  
  private final RectF m_dirtyRect = new RectF();  
  public Signature(Context context, AttributeSet attrs) {  
   super(context, attrs);  
   m_paint.setAntiAlias(true);  
   new ColorPickerDialog(context, new OnColorChangedListener() {  
   public void colorChanged(int color) {  
    m_paint.setColor(color);  
    mColor = color;  
   }  
   }, 0xFFFF0000).show();  
   m_paint.setStyle(Paint.Style.STROKE);  
   m_paint.setStrokeJoin(Paint.Join.ROUND);  
   m_paint.setStrokeWidth(STROKE_WIDTH);  
  }  

Now all that is left is to make sure that we add points to the path when we move our finger over the screen. Edit the onTouchEvent like below:

  @Override  
  public boolean onTouchEvent(MotionEvent event) {  
   float m_eventX = event.getX();  
   float m_eventY = event.getY();  
   switch (event.getAction()) {  
   case MotionEvent.ACTION_DOWN:  
   m_path.moveTo(m_eventX, m_eventY);  
   m_lastTouchX = m_eventX;  
   m_lastTouchY = m_eventY;  
   return true;  
   case MotionEvent.ACTION_MOVE:  
   case MotionEvent.ACTION_UP:  
   resetDirtyRect(m_eventX, m_eventY);  
   int historySize = event.getHistorySize();  
   for (int i = 0; i < historySize; i++) {  
    float historicalX = event.getHistoricalX(i);  
    float historicalY = event.getHistoricalY(i);  
    expandDirtyRect(historicalX, historicalY);  
    m_path.lineTo(historicalX, historicalY);  
   }  
   m_path.lineTo(m_eventX, m_eventY);  
   break;  
   default:  
   debug("Ignored touch event: " + event.toString());  
   return false;  
   }  
   invalidate((int) (m_dirtyRect.left - HALF_STROKE_WIDTH),  
    (int) (m_dirtyRect.top - HALF_STROKE_WIDTH),  
    (int) (m_dirtyRect.right + HALF_STROKE_WIDTH),  
    (int) (m_dirtyRect.bottom + HALF_STROKE_WIDTH));  
   m_lastTouchX = m_eventX;  
   m_lastTouchY = m_eventY;  
   return true;  
  }  
            /**  
   * This method checks the earlier rectangle.  
   *   
   * @param historicalX  
   * @param historicalY  
   */  
  private void expandDirtyRect(float historicalX, float historicalY) {  
   if (historicalX < m_dirtyRect.left) {  
   m_dirtyRect.left = historicalX;  
   } else if (historicalX > m_dirtyRect.right) {  
   m_dirtyRect.right = historicalX;  
   }  
   if (historicalY < m_dirtyRect.top) {  
   m_dirtyRect.top = historicalY;  
   } else if (historicalY > m_dirtyRect.bottom) {  
   m_dirtyRect.bottom = historicalY;  
   }  
  }  
  /**  
   * This method resets rectangle.  
   *   
   * @param eventX  
   * @param eventY  
   */  
  private void resetDirtyRect(float eventX, float eventY) {  
   m_dirtyRect.left = Math.min(m_lastTouchX, eventX);  
   m_dirtyRect.right = Math.max(m_lastTouchX, eventX);  
   m_dirtyRect.top = Math.min(m_lastTouchY, eventY);  
   m_dirtyRect.bottom = Math.max(m_lastTouchY, eventY);  
  }  

onTouch method is called when a touch event is dispatched to a view. This allows a listeners to get chance to respond before the target view.

   public boolean onTouch(MotionEvent event)      
  • event - is object of MotionEvent containing full information about event
In the code above, is first store the X and Y coordinates of the event (the touch or the moving of your finger) in variables. We then put in a switch statement to identify the type of event that was fired. In this case we need to create a new starting point for the path if the event is of type MotionEvent.ACTION_DOWN, which means we placed our finger on the screen, and connect points on MotionEvent.ACTION_MOVE which is when we moved our finger.

Next, We save the drawing into sdcard as an image. 

Output:







Thursday 10 April 2014

Create different Selectors in Android

           

In Android GUI is always an important part of any application, because ordinary users don't know and don't care about what's behind the scene; they want something easy to work with and now a days attractive GUI is a must for most applications.

Although making an appealing and innovative interface needs something more than just programming skills and knowledge, every programmer should know how to customize different GUI components within whatever framework and environment they are working.When designing GUIs, most of the times you want to change the appearance of buttons, input Fields, menus etc.. 

Android Selectors have been provided to solve all these kind of problems, they enable us to decide what to show and how to show based on different states of each components.

For example. You can tell a button to have black background color with red text color when it is in pressed state or whatever else.

So today i am going to show you how you can create selectors for Buttons with single color,two color and three color of layers.

Step 1: Create Project and add resources.

First of all create a simple android project in your workspace. 
After creating project Prepare/select any two images for Button states and put it into res/drawable folder.

1. "btn_selector_img.png"  -Default image of Button
2. "btn_selector_hv_img.png" - Display when the Button is Pressed.


Step 2: Create xml resources for the different types of selectors in res/drawable folder


1. Simple Image selector for showing images for pressed and unpressed states 

 image_selector.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:drawable="@drawable/btn_selector_hv_img" android:state_pressed="true"/>  
   <item android:drawable="@drawable/btn_selector_img"/>  
 </selector>  
 2.Simple Color selector to show different colors on Button when pressed or unpressed.  
   color_selector.xml  
 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:drawable="@color/yellow" android:state_pressed="true"/>  
   <item android:drawable="@color/pink"/>  
 </selector>  

2.Simple Color selector to show different colors on Button when pressed or unpressed.

  color_selector.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:drawable="@color/yellow" android:state_pressed="true"/>  
   <item android:drawable="@color/pink"/>  
 </selector>  

3.Two Color selector to show different colors on Button when pressed or unpressed.

two_color_selector.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:state_pressed="true">  
     <shape xmlns:android="http://schemas.android.com/apk/res/android">  
       <gradient android:angle="90" android:endColor="@color/yellow" android:startColor="@color/pink"   
         android:type="linear" />  
     </shape>  
     </item>  
   <item>  
     <shape xmlns:android="http://schemas.android.com/apk/res/android">  
       <gradient android:angle="90" android:endColor="@color/pink" android:startColor="@color/yellow"  
          android:type="linear" />  
     </shape>  
     </item>  
 </selector>  

4.Three Color selector to show different colors on Button when pressed or unpressed.

three_color_selector.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:state_pressed="true">  
     <shape xmlns:android="http://schemas.android.com/apk/res/android">  
       <gradient android:angle="90" android:centerColor="@color/white" android:endColor="@color/pink"   
         android:startColor="@color/yellow" android:type="linear" />  
     </shape>  
   </item>  
   <item>  
     <shape xmlns:android="http://schemas.android.com/apk/res/android">  
       <gradient android:angle="90" android:centerColor="@color/white" android:endColor="@color/yellow"   
         android:startColor="@color/pink" android:type="linear" />  
     </shape>  
    </item>  
 </selector>  

Step 3: Create layout xml 

 <?xml version="1.0" encoding="utf-8"?>  
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent" >  
   <LinearLayout  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:gravity="center_vertical|center"  
     android:orientation="vertical" >  
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginTop="20dip"  
       android:text="@string/title_selector_type"  
       android:textSize="20dp"  
       android:textStyle="bold" />  
     <!-- When you use image view then the attribute "android:clickable" must be set to "true" -->  
     <Button  
       android:layout_width="250dp"  
       android:layout_height="60dp"  
       android:layout_marginTop="20dip"  
       android:background="@drawable/image_selector"  
       android:text="@string/image_selector" />  
     <Button  
       android:layout_width="250dp"  
       android:layout_height="60dp"  
       android:layout_marginTop="20dip"  
       android:background="@drawable/color_selector"  
       android:text="@string/single_color_selector" />  
     <Button  
       android:layout_width="250dp"  
       android:layout_height="60dp"  
       android:layout_marginTop="20dip"  
       android:background="@drawable/two_color_gradiant_selector"  
       android:text="@string/two_color_selector" />  
     <Button  
       android:layout_width="250dp"  
       android:layout_height="60dp"  
       android:layout_marginTop="20dip"  
       android:background="@drawable/three_color_gradiant_selector"  
       android:text="@string/three_color_selector" />  
     <Button  
       android:layout_width="250dp"  
       android:layout_height="60dp"  
       android:layout_marginTop="20dip"  
       android:textStyle="bold"  
       android:background="@drawable/color_selector"  
       android:text="@string/gradiant_font_selector"  
       android:textColor="@color/text_selector" />  
   </LinearLayout>  
 </ScrollView>  

Tuesday 8 April 2014

Tinder App like Control with Animation in Android

Hello Friends,

You must have understood from the title only what i am going to share with you now. I think you must have checked the Tinder App on play store. Tinder app is a social application which will allow you to find the people nearby and chat with them. 

This application contains the nice control of like/dislike the people by swipe right or left. That animated control is already available ready for the iOS Tinder animation, but for android its not available as far as my knowledge. 

So i have tried to create similar kind of control for android and that is what today i  am going to share with you. 

Here are the screenshots of the view which i have developed. 





You can Download Source Code also. 

I hope it will help you. Feel free to give you suggestions and improve the control also. 

Thank you.

Thursday 3 April 2014

Android Custom Dialog Example

How to create custom dialog in Android

Hello, Friends.

Today i am going to show you that how you can customize Dialog in Android using custom layout file.

      Dialog box is mainly a popup or we can say a prompt that opens in front of the current activity to perform some operation or functionality.
          You can use a dialog box to ask the user to confirm an action, notify the user of an event, or prompt the user for additional information. Because dialog boxes disrupt the flow of the UI, you should use them only as a last resort. In most cases, you should integrate confirmation, feedback, and prompts directly into your app.

Sometimes in our applications we want to alert the user for an event and/or ask user about taking a decision. For this purpose AlertDialog class can be used, where a message and one, two or three buttons are displayed in a popup window.

       When a dialog box opens the current activity by which we open the dialog box goes to the background and the dialog box comes in the foreground. After performing the operation on the dialog box we dismiss the dialog box and the background activity comes back to the foreground. 


To create custom dialog first of all create simple Android application in eclipse.

Create a project with the following details:
  • ProjectNameCustomDialog 
  • PackageName: com.demo.customdialog
  • ActivityNameCustomDialogActivity

In your CustomDialogActivity write the code as below:

 import android.app.Activity;  
 import android.app.Dialog;  
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.view.Window;  
 import android.widget.Button;  
 import android.widget.LinearLayout;  
 import android.widget.ScrollView;  
 import android.widget.Toast;  
 import com.wli.framework.model.ClearActivityObjectListner;  
 import com.wli.framework.view.ActivityHelper;  
 public class CustomDialogActivity extends Activity implements OnClickListener  
 {  
  private static final int SIMPLE_DIALOG = 0;  
  private static final int BORDER_DIALOG = 1;  
  private static final int ROUNDE_CORNER_DIALOG = 2;  
  private static final int ROUNDE_CORNER_BORDER_DIALOG = 3;  
  private Dialog m_dialog; //Dialog instance.  
  private Button m_btnSimpleDialog, m_btnBorderDialog, m_btnRoundeCornerDialog, m_btnRoundeCornerBorderDialog;  
  private ScrollView m_svMain;  
  private LinearLayout m_llMain;  
  @Override  
  protected void onCreate(Bundle p_savedInstanceState)  
  {  
  super.onCreate(p_savedInstanceState);  
  setContentView(R.layout.maindialog_layout);  
  m_btnSimpleDialog = (Button) findViewById(R.id.dlbtnSimpleDialog);  
  m_btnBorderDialog = (Button) findViewById(R.id.dlbtnBorderDialog);  
  m_btnRoundeCornerDialog = (Button) findViewById(R.id.dlbtnRoundeCornerDialog);  
  m_btnRoundeCornerBorderDialog = (Button) findViewById(R.id.dlbtnRoundeCornerBorderDialog);  
  m_svMain = (ScrollView) findViewById(R.id.dlsvMain);  
  m_btnSimpleDialog.setOnClickListener(this);  
  m_btnBorderDialog.setOnClickListener(this);  
  m_btnRoundeCornerDialog.setOnClickListener(this);  
  m_btnRoundeCornerBorderDialog.setOnClickListener(this);  
  }  
  /**  
  * This is method to show customize dialog.  
  *   
  * @param p_index  
  *      - index of customize dialog  
  */  
  public void showCustomDialog(int p_index)  
  {  
  m_dialog = new Dialog(CustomDialogActivity.this, R.style.Dialog_No_Border);  
  m_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  LayoutInflater m_inflater = LayoutInflater.from(CustomDialogActivity.this);  
  View m_view = m_inflater.inflate(R.layout.custom_dialog, null);  
  m_llMain = (LinearLayout) m_view.findViewById(R.id.cadllMain);  
  //Change the background of the dialog according to the layout.   
  if (p_index == BORDER_DIALOG)  
  {  
   m_llMain.setBackgroundResource(R.drawable.btn_style_border);  
  }  
  else if (p_index == ROUNDE_CORNER_DIALOG)  
  {  
   m_llMain.setBackgroundResource(R.drawable.btn_style_roundcorner);  
  }  
  else if (p_index == ROUNDE_CORNER_BORDER_DIALOG)  
  {  
   m_llMain.setBackgroundResource(R.drawable.btn_style_border_roundcorner);  
  }  
  Button m_btnOk = (Button) m_view.findViewById(R.id.cadbtnOk);  
  Button m_btnCancel = (Button) m_view.findViewById(R.id.cadbtnCancel);  
  OnClickListener m_clickListener = new OnClickListener(){  
   @Override  
   public void onClick(View p_v)  
   {  
   Toast.makeText(CustomDialogActivity.this, "Pressed " + ((Button) p_v).getText(), Toast.LENGTH_SHORT).show();  
   switch (p_v.getId())  
    {  
    case R.id.cadbtnOk:  
     m_dialog.dismiss();  
    break;  
    case R.id.cadbtnCancel:  
     m_dialog.dismiss();  
     break;  
    default:  
     break;  
    }  
   }  
  };  
  m_btnOk.setOnClickListener(m_clickListener);  
  m_btnCancel.setOnClickListener(m_clickListener);  
  m_dialog.setContentView(m_view);  
  m_dialog.show();  
  }  
  /**  
  * Common click listener for the buttons.  
  */  
  @Override  
  public void onClick(View p_v)  
  {  
  switch (p_v.getId())  
   {  
   case R.id.dlbtnSimpleDialog:  
    showCustomDialog(SIMPLE_DIALOG);  
    break;  
   case R.id.dlbtnBorderDialog:  
    showCustomDialog(BORDER_DIALOG);  
    break;  
   case R.id.dlbtnRoundeCornerDialog:  
    showCustomDialog(ROUNDE_CORNER_DIALOG);  
    break;  
   case R.id.dlbtnRoundeCornerBorderDialog:  
    showCustomDialog(ROUNDE_CORNER_BORDER_DIALOG);  
    break;  
   default:  
    break;  
   }  
  }  
  public void clearView()  
  {  
  m_dialog = null;  
  m_btnSimpleDialog = null;  
  m_btnBorderDialog = null;  
  m_btnRoundeCornerDialog = null;  
  m_btnRoundeCornerBorderDialog = null;  
  m_svMain = null;  
  m_llMain = null;  
  }  
  @Override  
  protected void onDestroy()  
  {  
  super.onDestroy();  
  clearView();  
  }  
 }  

Here is the layout code. Create the layouts for the activity and dialog as below:

maindialog_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
   android:id="@+id/dlsvMain"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent" >  
   <LinearLayout  
     android:layout_width="fill_parent"  
     android:layout_height="fill_parent"  
     android:gravity="center_horizontal"  
     android:orientation="vertical"  
     android:paddingTop="80dp" >  
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:text="@string/title_customdialog"  
       android:textSize="25sp"  
       android:textStyle="bold" />  
     <Button  
       android:id="@+id/dlbtnSimpleDialog"  
       style="@style/commonButtonStyle"  
       android:text="@string/dl_simple_dialog" />  
     <Button  
       android:id="@+id/dlbtnBorderDialog"  
       style="@style/commonButtonStyle"  
       android:text="@string/dl_border_dialog" />  
     <Button  
       android:id="@+id/dlbtnRoundeCornerDialog"  
       style="@style/commonButtonStyle"  
       android:text="@string/dl_roundcorner_dialog" />  
     <Button  
       android:id="@+id/dlbtnRoundeCornerBorderDialog"  
       style="@style/commonButtonStyle"  
       android:text="@string/dl_roundcorner_border_dialog" />  
   </LinearLayout>  
 </ScrollView>  

custom_dialog.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:id="@+id/cadllMain"  
   android:layout_width="wrap_content"  
   android:layout_height="wrap_content"  
   android:background="@color/grey"  
   android:orientation="vertical"  
   tools:ignore="ButtonOrder" >  
   <FrameLayout  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content" >  
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:padding="10dp"  
       android:text="@string/title_text" />  
     <ImageView  
       android:id="@+id/imageView_close"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_gravity="top|right"  
       android:clickable="true"  
       android:src="@drawable/cancel"  
       android:visibility="gone"  
       tools:ignore="ContentDescription" />  
   </FrameLayout>  
   <View  
     android:layout_width="fill_parent"  
     android:layout_height="1dp"  
     android:layout_marginLeft="3dp"  
     android:layout_marginRight="3dp"  
     android:background="@android:color/white" />  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:lines="3"  
     android:padding="10dp"  
     android:text="@string/message" />  
   <LinearLayout  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:gravity="center_horizontal"  
     android:orientation="horizontal" >  
     <Button  
       android:id="@+id/cadbtnOk"  
       android:layout_width="100dp"  
       android:layout_height="40dp"  
       android:layout_margin="10dp"  
       android:background="@android:color/darker_gray"  
       android:text="@android:string/ok" />  
     <Button  
       android:id="@+id/cadbtnCancel"  
       android:layout_width="100dp"  
       android:layout_height="40dp"  
       android:layout_margin="10dp"  
       android:background="@android:color/darker_gray"  
       android:text="@android:string/cancel" />  
   </LinearLayout>  
 </LinearLayout>  

Copy the below code into your res/style file

style.xml

 <style name="Dialog_No_Border">  
     <item name="android:windowIsFloating">true</item>  
     <item name="android:windowBackground">@color/transparent_color</item>  
   </style>  
   <style name="commonButtonStyle">  
     <item name="android:layout_width">wrap_content</item>  
     <item name="android:layout_height">wrap_content</item>  
     <item name="android:layout_gravity">center_horizontal</item>  
     <item name="android:layout_margin">10dp</item>  
   </style>  

color.xml
 <color name="transparent_color">#00000000</color>  
 <color name="light_green">#00AA00</color>  
 <color name="grey">#DCDCDC</color>  

strings.xml
  <string name="title_activity_custom_dialog">CustomDialogActivity</string>  
   <string name="title_customdialog">Various Custom Dialogs</string>  
   <string name="dl_simple_dialog">Simple Custom Dialog</string>  
   <string name="dl_border_dialog">Custom Dialog with Border</string>  
   <string name="dl_roundcorner_dialog">Custom Dialog with Round Corner</string>  
   <string name="dl_roundcorner_border_dialog">Custom Dialog with Round Corner &amp; Border</string>  
   <string name="title_text">Add Title Text</string>  
   <string name="message">Alert Message...</string>  

Here is the AndroidManifest.xml file

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.demo.customdialog"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk  
     android:minSdkVersion="8"  
     android:targetSdkVersion="15" />  
   <application  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >  
     <activity  
       android:name="com.demo.customdialog.CustomDialogActivity"  
       android:label="@string/title_activity_custom_dialog" >  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
   </application>  
 </manifest>  

Output:




You can Download sourcode HERE

Monday 20 January 2014

Android Storage system to access the path of External and Internal files and folders.


Android uses more than one file system (think of "multiple drives/partitions" when comparing with your computer, while sharing a common base, directory structures might differ between manufacturers.


What is a file system?

            A file system (or filesystem) is an abstraction to store, retrieve and update a set of files. The term also identifies the data structures specified by some of those abstractions, which are designed to organize multiple files as a single stream of bytes, and the network protocols specified by some other of those abstractions, which are designed to allow files on a remote machine to be accessed.


Android supports different file systems:
  • FAT: Used mainly for SDCards. This system is supported by most operating systems (Windows, Linux, Mac, etc.), which is why it's used for these "exchangeables". But it is also quite restricted, which is why it is rarely used somewhere else.
  • exFAT: sometimes used instead of FAT -- but not generally supported
  • extfs: The extended file system already has seen several generations. Android devices usually support ext2, ext3, and in most cases also ext4.
  • YAFFS: A Log structured file system designed for NAND flash, but also used with NOR flash. This was often used for e.g. the /data partition with many devices up to Android 2.x

There are also some pseudo-filesystems used on Unix/Linux system in general and on Android devices in special:
  • devfs: Virtual file system for managing devices on-the-fly
  • procfs: Pseudo-file system, used to access kernel information about processes
  • sysfs: Virtual file system holding information about buses, devices, firmware, filesystems, etc.


Internal storage of Android devices is devided into several partitions, each dedicated to a special "task". 

Some of the more important ones include:

/system: This is where the Android system and the pre-installed apps reside. It usually is mounted read-only, so on non-rooted devices you cannot write here (with the exception of applying a system update, e.g. OTA, or flashing a new ROM)

/data: Here the downloaded apps and all app's data are located. Additionally, some system settings are stored here, log files, and more

Your sdcard usually has a single partition only -- but also could be split into multiple partitions. 

Below are some of the ways i am showing you to access the various files and folders in android file system:

System directories
Method
Result
Environment.getDataDirectory()
/data
Environment.getDownloadCacheDirectory()
/cache
Environment.getRootDirectory()
/system
External storage directories
Method
Result
Environment.getExternalStorageDirectory()
/storage/sdcard0
Environment.getExternalStoragePublicDirectory(DIRECTORY_ALARMS)
/storage/sdcard0/Alarms
Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM)
/storage/sdcard0/DCIM
Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS)
/storage/sdcard0/Download
Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES)
/storage/sdcard0/Movies
Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC)
/storage/sdcard0/Music
Environment.getExternalStoragePublicDirectory(DIRECTORY_NOTIFICATIONS)
/storage/sdcard0/Notifications
Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES)
/storage/sdcard0/Pictures
Environment.getExternalStoragePublicDirectory(DIRECTORY_PODCASTS)
/storage/sdcard0/Podcasts
Environment.getExternalStoragePublicDirectory(DIRECTORY_RINGTONES)
/storage/sdcard0/Ringtones

Application directories
Method
Result
getCacheDir()
/data/data/package/cache
getFilesDir()
/data/data/package/files
getFilesDir().getParent()
/data/data/package
Application External storage directories
Method
Result
getExternalCacheDir()
/storage/sdcard0/Android/data/package/cache
getExternalFilesDir(null)
/storage/sdcard0/Android/data/package/files
getExternalFilesDir(DIRECTORY_ALARMS)
/storage/sdcard0/Android/data/package/files/Alarms
getExternalFilesDir(DIRECTORY_DCIM)
/storage/sdcard0/Android/data/package/files/DCIM
getExternalFilesDir(DIRECTORY_DOWNLOADS)
/storage/sdcard0/Android/data/package/files/Download
getExternalFilesDir(DIRECTORY_MOVIES)
/storage/sdcard0/Android/data/package/files/Movies
getExternalFilesDir(DIRECTORY_MUSIC)
/storage/sdcard0/Android/data/package/files/Music
getExternalFilesDir(DIRECTORY_NOTIFICATIONS)
/storage/sdcard0/Android/data/package/files/Notifications
getExternalFilesDir(DIRECTORY_PICTURES)
/storage/sdcard0/Android/data/package/files/Pictures
getExternalFilesDir(DIRECTORY_PODCASTS)
/storage/sdcard0/Android/data/package/files/Podcasts
getExternalFilesDir(DIRECTORY_RINGTONES)
/storage/sdcard0/Android/data/package/files/Ringtones


Thanks.