Android Animations

February 10th, 2012 No comments

Android provides two mechanisms that you can use to create simple animations:
Tweened animation , in which you tell Android to perform a series of simple transformations (position, size, rotation, and so on) to the content of a View; and Frame-By-Frame animation, which loads a series of Drawable resources one after the other. Both animation types can be used in any View object to provide simple rotating timers, activity icons, and other useful UI elements

1. Tweened Animation

Android can perform simple visual transformations for you, including straight line motion, size change, and transparency change, on the contents of a View object. These transformations are represented by the following classes:

  • AlphaAnimation (transparency changes)
  • RotateAnimation (rotations)
  • ScaleAnimation (growing or shrinking)
  • TranslateAnimation (position changes)

This animations can be highly customized and combined, for example we can set the speed, delay, acceleration, duration of animations, then group them together in an AnimationSet.

The animations can be defined in XMl or by code. Defining in xml is much more clear, but you can not set animation parameters dynamically.

The animation XML files should be created in the res/anim folder and can be accessed using R.anim.animation_name.

Project setup

We are going to load our animations for a ImageView used in an activity – so set up a new Android project. Add a ImageView to your main.xml

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

	<ImageView android:id="@+id/iv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon"
      />

</LinearLayout>


Create a new Activity named AnimationActivity

package com.mobisys.android.twin_animation_ex;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
public class TwinAnimationActivity extends Activity {
 /** Called when the activity is first created. */
 @Override public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 final ImageView iv = (ImageView) findViewById(R.id.iv1);
 LinearLayout layout = (LinearLayout) findViewById(R.id.root);
 }
}


Alpha Animations

Alpha animations allows us to create fade-in/fade-out effects.
All animations are stored in res/anim so we create a new xml file named alpha.xml there.

Attributes:

android:fromAlpha
Float. Starting opacity offset, where 0.0 is transparent and 1.0 is opaque.
android:toAlpha
Float. Ending opacity offset, where 0.0 is transparent and 1.0 is opaque.


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

<alpha
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:fromAlpha="1.0"
 android:toAlpha="0.2"
 android:duration="4000" />


Note : The file must have a single root element: either an <alpha>, <scale>, <translate>, <rotate>, or <set> element that holds a group (or groups) of other animation elements (even nested <set> elements).

Change the activity to load the animation from the xml file and start the animation

package com.mobisys.android.animation_demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class AnimationActivity extends Activity {
    /** Called when the activity is first created. */
	ImageView imageView;
	Animation a;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView=(ImageView)findViewById(R.id.iv1);
        a = AnimationUtils.loadAnimation(this, R.anim.alpha);
        a.reset();
        imageView.startAnimation(a);

    }
}


Rotate Animations

A rotation animation.

Attributes:

android:fromDegrees
Float. Starting angular position, in degrees.
android:toDegrees
Float. Ending angular position, in degrees.
android:pivotX
Float or percentage. The X coordinate of the center of rotation. Expressed either: in pixels relative to the object’s left edge (such as “5″), in percentage relative to the object’s left edge (such as “5%”), or in percentage relative to the parent container’s left edge (such as “5%p”).
android:pivotY
Float or percentage. The Y coordinate of the center of rotation. Expressed either: in pixels relative to the object’s top edge (such as “5″), in percentage relative to the object’s top edge (such as “5%”), or in percentage relative to the parent container’s top edge (such as “5%p”).

Add a new xml file to res/anim named rotate.xml

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

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
	 android:fromDegrees="0"
	 android:toDegrees="360"
	 android:pivotX="50%"
	 android:pivotY="50%"
	 android:duration="4000" />


Replace the alpha rotation with the new rotation animation in your activity.

Animation a = AnimationUtils.loadAnimation(this, R.anim.rotate);


Scale Animations

A resizing animation. You can specify the center point of the image from which it grows outward (or inward) by specifying pivotX and pivotY.

Attributes:

android:fromXScale
Float. Starting X size offset, where 1.0 is no change.
android:toXScale
Float. Ending X size offset, where 1.0 is no change.
android:fromYScale
Float. Starting Y size offset, where 1.0 is no change.
android:toYScale
Float. Ending Y size offset, where 1.0 is no change.
android:pivotX
Float. The X coordinate to remain fixed when the object is scaled.
android:pivotY
Float. The Y coordinate to remain fixed when the object is scaled.

Create another XML file in res/anim named scale.xml

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"

            android:fromXScale="3.0"
            android:toXScale="1.0"
            android:fromYScale="3.0"
            android:toYScale="1.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="4000" />


Load the animation in your activity.

Animation a = AnimationUtils.loadAnimation(this, R.anim.scale);


Translate Animations

A vertical and/or horizontal motion. Supports the following attributes in any of the following three formats: values from -100 to 100 ending with “%”, indicating a percentage relative to itself; values from -100 to 100 ending in “%p”, indicating a percentage relative to its parent; a float value with no suffix, indicating an absolute value.

Attributes:

android:fromXDelta
Float or percentage. Starting X offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element width (such as “5%”), or in percentage relative to the parent width (such as “5%p”).

android:toXDelta
Float or percentage. Ending X offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element width (such as “5%”), or in percentage relative to the parent width (such as “5%p”).

android:fromYDelta
Float or percentage. Starting Y offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element height (such as “5%”), or in percentage relative to the parent height (such as “5%p”).

android:toYDelta
Float or percentage. Ending Y offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element height (such as “5%”), or in percentage relative to the parent height (such as “5%p”).

Create translate.xml in res/anim

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true">

	<translate android:fromXDelta="0"
	    android:toXDelta="30"
	    android:duration="4000"
	    android:fillAfter="true"/>

	<translate android:toYDelta="100"
        android:fillAfter="true"
        android:duration="4000"
        android:startOffset="4000"/>
 </set>


here <set>: A container that holds other animation elements (<alpha>, <scale>, <translate>, <rotate>) or other <set> elements.(i.e <set> contains multiple animation elements)

and android:fillAfter : When set to true, the animation transformation is applied after the animation is over.

Replace the animation in your activity

Animation a = AnimationUtils.loadAnimation(this, R.anim.translate);


2. Frame By Frame Animation

An object used to create frame-by-frame animations, defined by a series of Drawable objects, which can be used as a View object’s background.

The simplest way to create a frame-by-frame animation is to define the animation in an XML file, placed in the res/anim, and set it as the background to a View object. Then, call start() to run the animation.

An AnimationDrawable defined in XML consists of a single <animation-list> element, and a series of nested tags. Each item defines a frame of the animation.

Firstly,we will define ImageView in main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">

    <ImageView android:id="@+id/img"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"/>

</LinearLayout>


spin_animation.xml file in res/anim/ folder:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
	android:oneshot="false">
    <item android:drawable="@drawable/blue_baloon" android:duration="1000" />
    <item android:drawable="@drawable/orange_baloon" android:duration="1000" />
    <item android:drawable="@drawable/red_baloon" android:duration="1000" />

</animation-list>



You can download images here

Here is the code to load and play this animation.

package com.mobisys.android.frame_by_frame;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class FrameActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus){

    	ImageView img=(ImageView)findViewById(R.id.img);
        img.setBackgroundResource(R.anim.spin_animation);
        AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
        frameAnimation.start();
    }
}


Here don’t start animation until window’s focus get changed. So never start the animation in onCreate().
So for that override the method onWindowFocusChanged() and start animation in this method.

Run the application. :-)

Android Fonts

January 28th, 2012 No comments

Every Android device comes with a collection of standard fonts: Droid Sans, Droid Sans Mono and Droid Serif. They were designed to be optimal for mobile displays, so these are the three fonts you will be working with most of the time and they can be styled using a handful of XML attributes. You might, however, see the need to use custom fonts for special purposes. We’ll be taking a look at that as well.

Font Style Attributes

In the following section we’re going to examine the different XML attributes that you can use to style components with text.

Typeface

As stated in the overview, there are three different default typefaces which are known as the Droid family of fonts: sans, monospace and serif. You can specify any one of them as the value for the android:typeface attribute in the XML declaration of a component that supports text styling, such as TextView. Here’s an example of all three typefaces in action:

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

	<TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/hello"/>

	<TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Normal"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>

    <TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Serif"
	    android:typeface="serif"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>

	<TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Sans"
	    android:typeface="sans"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>    

    <TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Monospace"
	    android:typeface="monospace"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>
</LinearLayout>


In addition to the above, there is another attribute value named “normal” which defaults to the sans typeface.

DROID family & normal font


Using Custom Fonts

We’ll use Garamond.TTF font for demonstration purposes. Download it and place the TTF file in the ./assets directory (create it if it doesn’t exist yet).
We’re going to use a basic layout file with a TextView, marked with an id of “custom_font” so we can access it in our code.

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

      <TextView android:id="@+id/custom_font"
	 	android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:text="This is garamond Font"/>


Open your main activity file and insert this into the onCreate() method:

TextView t=(TextView)findViewById(R.id.custom_font);
        Typeface font=Typeface.createFromAsset(getAssets(), "Garamond.TTF");
        t.setTypeface(font);


The Typeface class contains a static builder method createFromAsset, which takes an AssetManager as its first parameter and a path to the file in the second argument. We’re handing it the default asset manager and the name of the font file because it’s located in the root of the “assets” folder. Once we’ve got an instance of our custom typeface, all that’s left is a call to TextView’s setTypeface() method.

Custom Font

>

Text Style

The android:textStyle attribute can be used to put emphasis on text. The possible values are: normal, bold, italic. You can also specify bold|italic.

<TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="This is bold!"
            android:textStyle="bold"  />


Text Style


Text Size

android:textSize specifies the font size. Its value must consist of two parts: a floating-point number followed by a unit. Available units are: sp (scaled pixels), px (pixels), dp (density-independent pixels), in (inches), mm (millimeters). It is generally a good practice to use the sp unit so that it will be consistent across all screen resolutions.

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="15sp is the 'normal' size."
        android:textSize="15sp" />



Text Size


Text Color

The android:textColor attribute’s value is a hexadecimal RGB value.

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="A light blue color."
            android:textColor="#00ccff"
            />



SMS Messaging in Android

January 26th, 2012 No comments

In this article, we take a look at how you can programmatically send and receive SMS messages in your Android applications. The good news for Android developers is that you don’t need a real device to test out SMS messaging – the free Android emulator provides the capability to do so.

Sending SMS Messages

Create project named com.mobisys.android.sms_messaging having activity SMSActivity in it.

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:


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

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


In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the phone number of recipient"
        />
    <EditText
        android:id="@+id/txtPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Message"
        />
    <EditText
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"
        />
    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />
</LinearLayout>


The above code creates the UI :

Creating the UI for sending SMS messages


Next, in the SMSActivity, when the user clicks on Button, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function.

package com.mobisys.android.sms_messaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMSActivity extends Activity
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

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

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();
                if (phoneNo.length()>0 && message.length()>0)
                    sendSMS(phoneNo, message);
                else
                    Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

The sendSMS() function is defined as follows:


private void sendSMS(String phoneNumber, String message)
    {
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMSActivity.class), 0);
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);
    }


To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity , so when the SMS is sent, nothing will happen.

If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:


private void sendSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }


The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver‘s onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver‘s onReceive event will fire when an SMS is successfully delivered.

You can now test the application.


Sending an SMS


Above figure shows how you can send an SMS message from one emulator to another; simply use the target emulator’s port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a “SMS sent” message. When it is successfully delivered, it will display a “SMS delivered” message. Note that for testing using the emulator, when an SMS is successfully delivered, the “SMS delivered” message does not appear; this only works for real devices.

Following figure shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

SMS message received by the Android Emulator



Receiving SMS Messages

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.
To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the element so that incoming SMS messages can be intercepted by the SmsReceiver class:

        <receiver android:name=".SmsReceiver">
            <intent-filter>
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>


Add a new class file to your project and name it as SmsReceiver.java

In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:

package com.mobisys.android.sms_messaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SmsReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
       {
	}
}


When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent – the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

package com.mobisys.android.sms_messaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                      

	}

}


All you need to do is to select each emulator and deploy the application onto each one.

Figure shows that when you send an SMS message to another emulator instance (port number 5554), the message is received by the target emulator and displayed via the Toast class.

Sending and receiving SMS messages using the Android emulators


Download Source code

Click here to download

Android Layouts : LinearLayout and RelativeLayout

January 20th, 2012 1 comment

In this tutorial we will be discussing about the different view layouts in an android mobile application. The six different layouts are

1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View

Android allows you to create view layouts using simple XML file. All the layouts must be placed in /res/layout folder.

Android Layout Directory


Mostly in many applications we use “Linear Layout” and “relative layout” only. So we will learn these layouts below.

Linear Layout

In a linear layout, like the name suggests, all the elements are displayed in a linear fashion, either Horizontally or Vertically and this behavior is set in android:orientation which is an attribute of the node LinearLayout.
i.e.
Example of Vertical layout

<LinearLayout android:orientation="vertical"> .... </LinearLayout>


Example of Horizontal layout

<LinearLayout android:orientation="horizontal"> .... </LinearLayout>

Let’s create project:
1) Create a new project File -> New -> Android Project
2) Create linear_layout.xml in res/layout and insert following

<?xml version="1.0" encoding="utf-8"?>
<!-- Parent linear layout with vertical orientation -->
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <TextView android:layout_width="fill_parent"
     		android:layout_height="wrap_content"
     		android:text="Email:" />

  <EditText android:layout_width="fill_parent"
     		android:layout_height="wrap_content"/>             

  <Button android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:text="Login"/>

  <!-- Child linear layout with horizontal orientation -->
  <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:background="#2a2a2a"
            android:layout_marginTop="10dp">

  <TextView android:layout_width="wrap_content"
  			android:layout_height="wrap_content"
            android:text="Home"
            android:gravity="center"/>

  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="About"
            android:paddingLeft="8dp"
            android:gravity="center"/>   

  </LinearLayout>

</LinearLayout>


Linear Layout Output

Here Email TextView, EditText and Login Button are vertical in layout. whereas Home and about are in horizontal layout.

Relative Layout

In a relative layout every element arranges itself relative to other elements or a parent element.

Relative To Container

These properties will layout elements relative to the parent container.

1) android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container

2) android:layout_alignParentLeft – Places the left of the element on the left side of the container

3) android:layout_alignParentRight – Places the right of the element on the right side of the container

4) android:layout_alignParentTop – Places the element at the top of the container

5) android:layout_centerHorizontal – Centers the element horizontally within its parent container

6) android:layout_centerInParent – Centers the element both horizontally and vertically within its container

7) android:layout_centerVertical – Centers the element vertically within its parent container

Example


<RelativeLayout
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
 		android:id="@+id/button01"
 		android:text="Top Button Horizontally center"
 		android:layout_alignParentTop="true"
 		android:layout_width="wrap_content"
 		android:textSize="10sp"
 		android:layout_centerHorizontal="true"
 		android:layout_height="wrap_content" />

	<Button
 		android:id="@+id/button02"
 		android:text="Bottom Button Horizontally center"
 		android:layout_alignParentBottom="true"
 		android:layout_width="wrap_content"
 		android:textSize="10sp"
 		android:layout_centerHorizontal="true"
 		android:layout_height="wrap_content" />

 	<Button
 		android:id="@+id/button03"
 		android:text="Left Button Vertically center"
 		android:layout_width="wrap_content"
 		android:textSize="10sp"
 		android:layout_alignParentLeft="true"
 		android:layout_centerVertical="true"
 		android:layout_height="wrap_content" />	

<Button
 		android:id="@+id/button04"
 		android:text="Right Button Vertically center"
 		android:layout_width="wrap_content"
 		android:layout_alignParentRight="true"

 		android:layout_centerVertical="true"
 		android:textSize="10sp"
 		android:layout_height="wrap_content" />
</RelativeLayout>



Relative Layout Output-1


Relative To Other Elements

These properties allow you to layout elements relative to other elements on screen.

1) android:layout_above – Places the element above the specified element

2) android:layout_below – Places the element below the specified element

3) android:layout_toLeftOf – Places the element to the left of the specified element

4) android:layout_toRightOf – Places the element to the right of the specified element

Example


<RelativeLayout
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
 		android:id="@+id/button01"
 		android:text="Button1"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content" />
	<Button
 		android:id="@+id/button02"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:layout_toRightOf="@id/button01"
 		android:layout_marginLeft="8dp"
 		android:text="To the RightOf Button1"/>
 	<Button
 		android:id="@+id/button03"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:layout_below="@id/button01"
 		android:layout_alignParentRight="true"
 		android:text="Button 2"/>
 	<Button
 		android:id="@+id/button04"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:layout_below="@id/button01"
 		android:layout_toLeftOf="@id/button03"
		android:text="To Left of Button 2"/>

</RelativeLayout>


Relative Layout output-2


Alignment With Other Elements

These Properties allow you to specify how elements are aligned in relation to other elements.

1) android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified element

2) android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified element

3) android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified element

4) android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified element

5) android:layout_alignTop – Places top of the new element in alignment with the top of the specified element

Example


<RelativeLayout
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
 		android:id="@+id/button01"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
		android:text="Button-2 right boundary aligned with this button"/>
	<Button
 		android:id="@+id/button02"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:text="Button-2"
 		android:layout_below="@id/button01"
 		android:layout_alignRight="@+id/button01"/>
</RelativeLayout>


UI Component: WebView

January 20th, 2012 No comments

A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages.

In this demo, we get to view a web address in a totally different way by sidestepping the default browser and creating our own custom webviewer.

The key to creating the custom webviewer is the MyWebViewClient class that extends the WebViewClient class. With its key method shouldOverrideUrlLoading(view,url) that gives control to application when a new url is loaded in the provided view.

Sample Example

1) Create a new project/Activity called UIActivity.

2) We will have EditText in which URL to be entered, Button and WebView.

So Open the layout file. Insert following:

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

    <LinearLayout
    	android:orientation="horizontal"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content">

	    <EditText
	    android:id="@+id/url"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:lines="1"
	    android:layout_weight="1.0"
	    android:hint="http://"/>

	    <Button
	    android:id="@+id/go_button"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:text="go"
	    />

    </LinearLayout>

	<WebView
		android:id="@+id/webview_compontent"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	/>
</LinearLayout>


3) Now open the UIActivity.java file. At the top of the class, instantiate a WebView object:

                private WebView webView;
		private EditText urlField;


Then add the following at the end of the onCreate() method:

                        webView  = (WebView) findViewById(R.id.webview_compontent);
		        urlField = (EditText)findViewById(R.id.url);

((Button)findViewById(R.id.go_button)).setOnClickListener(new View.OnClickListener(){

					@Override
					public void onClick(View v) {

						webView.loadUrl(urlField.getText().toString());

					}
		        });


This captures the WebView we created in our layout.
Here we can load a page, but as soon as we click a link, the default Android web browser handles the Intent, instead we will be handling actions in our own WebView.

4) Because we’re accessing the internet, we need to add the appropriate permissions to the Android manifest file. So open the AndroidManifest.xml file and, add the following as a child of the element:

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


So now we’ll override the WebViewClient to enable us to handle our own URL loading.

In the UIActivity, add this nested private class:

private class MyWebViewClient extends WebViewClient {
	        @Override
	        public boolean shouldOverrideUrlLoading(WebView view, String url) {
	            view.loadUrl(url);
	            return true;
	        }
	    }


Now, in the onCreate() method, set an instance of the HelloWebViewClient as our WebViewClient:

webView.setWebViewClient(new MyWebViewClient());



This line should immediately follow the initialization of our WebView object.

What we’ve done is create a WebViewClient that will load any URL selected in our WebView in the same WebView. You can see this in the shouldOverrideUrlLoading() method, above—it is passed the current WebView and the URL, so all we do is load the URL in the given view. Returning true says that we’ve handled the URL ourselves.

5) Run the application.

UI Components: Part-1

January 19th, 2012 3 comments

There are several UI components are exist. We will learn some basic components.

Button

Buttons can be pressed, or clicked, by the user to perform an action.
we can create Button by writing following code:

<Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:id="@+id/button"
     android:text="Click to Perform Action"/>



Attach listeners inside your activity “onCreate()” method to perform action,


        ((Button)findViewById(R.id.button)).setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				//Perform action here
			}
		});


TextView, EditText

Write layout file containing EditText with inputType set to to “text“, “number” and “textPassword” for alpha-numeric, numeric and password text respectively. Also add TextView which will be not editable. Default inputType of EditText is “text“.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

  <EditText android:id="@+id/edittext01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Text"/>

  <EditText android:id="@+id/edittext02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="Number"/>

    <EditText android:id="@+id/edittext03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:hint="Text password"/>  

</LinearLayout>


Getting Text value of EditText

str=text.getText().toString();
Toast.makeText(UIActivity.this,str, Toast.LENGTH_SHORT).show();


CheckBox

For CheckBox we can have

<CheckBox
        android:id="@+id/chkAnd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android" />


and to perform action

CheckBox ChkBx =(CheckBox)findViewById(R.id.chkAnd);

        ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub

			} });


RadioGroup and RadioButtons

This class is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group unchecks any previously checked radio button within the same group.

Intially, all of the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state.

The selection is identified by the unique id of the radio button as defined in the XML layout file.

xml file contains:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="RadioGroup"/>

<RadioGroup android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	android:id="@+id/radiogroup">

<RadioButton android:id="@+id/radiobutton1"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="radio1" >
</RadioButton>

<RadioButton android:id="@+id/radiobutton2"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="radio2">
</RadioButton>

<RadioButton android:id="@+id/radiobutton3"
	android:layout_width="wrap_content"
 	android:layout_height="wrap_content"
 	android:text="radio3">
 </RadioButton>

</RadioGroup>

</LinearLayout>


Whenever you will select radio button, the related messsage will be displayed
Note: You need to implement RadioGroup.OnCheckedChangeListener in main activity
i.e

package com.mobisys.android.ui_components;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class UIActivity extends Activity implements
RadioGroup.OnCheckedChangeListener{
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        RadioGroup rg = (RadioGroup) findViewById(R.id.radiogroup);
        rg.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup group, int checkedId) {
    	String radioButtonSelected = "";
    	switch (checkedId) {

        case R.id.radiobutton1 : radioButtonSelected = "radiobutton1";
                         	              break;
        case R.id.radiobutton2 : radioButtonSelected = "radiobutton2";
      		                      break;
        case R.id.radiobutton3 : radioButtonSelected = "radiobutton3";
      		                      break;

        }
    	Toast.makeText(UIActivity.this,radioButtonSelected+" Selected", Toast.LENGTH_SHORT).show();
    }
  }



ImageView

Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the image so that it can be used in any layout manager.

Setting image from Resource

Download the following folder and copy the images in res/drawable folder
images

xml contains:

<?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" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ok" />

    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" />

</LinearLayout>


When we click Button it changes the image as specified in setImageResource().

package com.mobisys.android.ui_components;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class UIActivity extends Activity{
    /** Called when the activity is first created. */
	ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.btnChangeImage)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {

				image = (ImageView) findViewById(R.id.imageView1);
				image.setImageResource(R.drawable.no);
			}

        });
}
}


Setting image from Bitmap

All this below code does is load the image icon.png from sdcard. The BitmapFactory creates a bitmap object with this image and we use the myImage.setImageBitmap() method to update the ImageView component.

You can use the above xml.

And for setting the image using Bitmap you can have

package com.mobisys.android.ui_components;

import java.io.File;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class UIActivity extends Activity{
    /** Called when the activity is first created. */
	ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.btnChangeImage)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				File imgFile = new  File(Environment.getExternalStorageDirectory()+"/Images/icon.png");

				if(imgFile.exists()){

				    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

				    ImageView myImage = (ImageView) findViewById(R.id.imageView1);
				    myImage.setImageBitmap(myBitmap);

				}

			}

        });
}
}


Spinner

Spinner is a widget similar to a drop-down list for selecting items.
you’ll create a simple spinner widget that contains a list of planets.

main.xml contains:

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="@string/planet_prompt"
    />
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/planet_prompt"
    />
</LinearLayout>


Create a strings.xml file in res/values/ and enter the following:

<string name="planet_prompt">Choose a planet</string>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>


and our java code will look like:

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

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.planets_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
}


output screens:


Toggle Button

Displays checked/unchecked states as a button with a “light” indicator and by default accompanied with the text “ON” or “OFF“.

layout file contains:

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

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<ToggleButton android:id="@+id/togglebutton"
android:layout_width="150px"
android:layout_height="50px"
android:textOn="ON"
android:textOff="OFF" />

</LinearLayout>


and java code will look like:

	public class UIActivity extends Activity
	{
		ToggleButton tb;

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

		        tb = (ToggleButton) findViewById(R.id.togglebutton);
		        tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){

					@Override
					public void onCheckedChanged(CompoundButton button,
							boolean isChecked) {

						if(isChecked)
							Toast.makeText(UIActivity.this, "Toggle Button is on", Toast.LENGTH_LONG).show();
						else
							Toast.makeText(UIActivity.this, "Toggle Button is off", Toast.LENGTH_LONG).show();;
					}

		        });

	}
	}



Toggle Off:

Toggle On:

UI Components: Part-2

January 19th, 2012 No comments

RatingBar

In Android, you can use “android.widget.RatingBar” to display rating bar component in stars icon. The user is able to touch, drag or click on the stars to set the rating value easily.

In this tutorial, we show you how to use XML to display a rating bar. When user click on the rating bar’s star, the selected rating value will be displayed as a toasted message.

layout file contains:

<?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/lblRateMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rate Me" />

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:stepSize="1.0"
        android:rating="0.0" />

 </LinearLayout>


Activity class implements the class RatingBar.OnRatingBarChangeListener i.e.

public class UIActivity extends Activity implements RatingBar.OnRatingBarChangeListener


Register the setOnRatingBarChangeListener(), so that we get notified in method onRatingChanged().


rate=(RatingBar)findViewById(R.id.ratingBar);// create RatingBar object
rate.setOnRatingBarChangeListener(this);



Display ratings by implementing abstract method onRatingChanged of OnRatingBarChangeListener


			public void onRatingChanged(RatingBar ratingBar,float rating, boolean fromUser){

				Toast.makeText(UIActivity.this,"Rating is : "+rating,Toast.LENGTH_SHORT).show();

			}      



SeekBar

The SeekBar is a slider with a maximum value with which you can select values from a range visually. The range of the seek bar is from 0 to the maximum value. We can set the maximum value using android:max attribute in layout file.

Layout file contains:

<?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:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="Seekbar"/>

    <SeekBar android:id="@+id/seekbar"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:max="100"
		android:minWidth="250px"  />

	<TextView android:id="@+id/textview"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />

</LinearLayout>


Our tutorial displays the changing value of the SeekBar as you drag it.
The SeekBar has three states: drag start, changing and drag ended.


package com.mobisys.android.ui_components;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

	public class UIActivity extends Activity
	{
		SeekBar seek;
		TextView value;

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

		        seek=(SeekBar)findViewById(R.id.seekbar);
		        value=(TextView)findViewById(R.id.textview);
		        seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
                       //drag change
					@Override
					public void onProgressChanged(SeekBar seekBar, int process,
							boolean fromUser) {

						value.setText("SeekBar Value is: "+process);
						Toast.makeText(UIActivity.this, "changing", Toast.LENGTH_LONG).show();
					}
                               // drag start
					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {

						Toast.makeText(UIActivity.this, "starting to track touch", Toast.LENGTH_LONG).show();
					}
                                 // Drag stop
					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {

						Toast.makeText(UIActivity.this, "Ended tracking touch", Toast.LENGTH_LONG).show();
					}

		        });
		}

	}


Method for drag start: runs when you first touch the bar.

Method for changing: this one gets executed as you drag the bar

Method for drag stop: runs when you let go of the bar

Gallery

A Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center.

layout file contains:

<?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" >

<Gallery
    android:id="@+id/Gallery01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</Gallery>

<ImageView android:id="@+id/ImageView01"
    android:layout_marginTop="8dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"></ImageView>

</LinearLayout>


It also has an ImageView element which is used to show the selected Image in a larger ImageView. Here is how it would look when executed.

Now, in our Activity,we created small sized images of antartica and stored them in the res/drawable folder starting form antartica1.png to antartica10.png.

we create an array of these resources/images in our activity with the following code:

Integer[] pics = {
R.drawable.antartica1,
R.drawable.antartica2,
R.drawable.antartica3,
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};


As we have seen with all the other views so far, we need to have an adapter that associates the view with the data. Here the view is Gallery and the data is the above mentioned 10 images. An Adapter plays the role of linking the two as shown below:


Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));



Now we will create our own implementation of ImageAdapter extending the BaseAdapter class.The moment we extend the BaseAdapter, we have to override 4 methods. They are getCount(), getItem(), getItemId() and getView().

Let us see the constructor of the ImageAdpater:

public class ImageAdapter extends BaseAdapter {

		    int mGalleryItemBackground;
		    private Context ctx;

		    public ImageAdapter(Context c) {
		        ctx = c;

		        TypedArray ta = c.obtainStyledAttributes(R.styleable.Gallery1);
		        mGalleryItemBackground = ta.getResourceId(
		                R.styleable.Gallery1_android_galleryItemBackground, 1);
		        ta.recycle();
		    }


It takes the context that is passed to the constructor. We need to examine this code a little. First, we can define our own resources or attributes in an XML file. Those attributes can be retrieved through the method obtainStyledAttributes. This is a method on the Context object. The returned value needs to be stored in a TypedArray object. A TypedArray is nothing but a container for an array of values that are returned by obtainStyledAttributes.

So, here we have created an xml file by name attributes.xml in the res/values folder with the following content:

<resources>
     <declare-styleable name="Gallery1">
    <attr name="android:galleryItemBackground"/>
     </declare-styleable>
</resources>


Here Gallery1 is a custom name for a style defined by us. In this style, we are trying to say what should be the background of our images. For that we are using a pre-defined backgournd in R.attr class as galleryItemBackground.

So, this is accessed in the ImageAdapter contructor through the line.

ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();


The number 1 is to say that it is the first element in the attributes.xml file under the styelable.Gallery1.

The rest of the overridden methods are:

@Override
public int getCount() {
    return pics.length;
}

@Override
public Object getItem(int pos) {
    return pos;
}

@Override
public long getItemId(int pos) {
    return pos;
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
    ImageView iv = new ImageView(ctx);
    iv.setImageResource(pics[arg0]);
    iv.setScaleType(ImageView.ScaleType.FIT_XY);
    iv.setLayoutParams(new Gallery.LayoutParams(150,120));
    iv.setBackgroundResource(mGalleryItemBackground);
    return iv;
}


The getView actually returns a View object when called. Here we have overridden it to return a ImageView object with the selected image inside it with some scale, layout paramaters and the image background set.

Finally in the onCreate() method of the activity we have captured the onClick event on a Gallery item and within that we have toasted a message as well as displayed the image.

ga.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
    Toast.makeText(UIActivity.this, "You have selected picture " + (pos+1) + " of Antartica",
        Toast.LENGTH_SHORT).show();
    imageView.setImageResource(pics[pos]);
}
});


Download Source code

Click here to download

Android: QR Code Encode and Decode using Zxing library

January 17th, 2012 7 comments

In this tutorial we will learn how to Encode and Decode the QR code.

Sample Example

Create project named “com.mobisys.android.qrcode_scanner” having activity “QrcodeActivity“.

Prerequisites:

1) Create libs folder in your project
2) Then You need to download core.jar file and copy this jar file into libs folder.
3) Add the core.jar file downloaded in step-2 in Java Build Path
i.e. right click on your project>Properties/Java Build Path/click on Add External JARs>select core.jar file>press ok




4)You need to download Zxing source code here.

5)Integrate the following packages in your project’s src folder i.e downloaded in step 4(go to folder ZXing-1.6\android\src\)

com.google.zxing.client.android
com.google.zxing.client.android.camera
com.google.zxing.client.android.encode
com.google.zxing.client.android.result



(i.e check the following screenshot)



6)Also add all the related Resource file from ZXing-1.6\android\res folder
(Check the following Resource directory structure which you need to be integrate)

Resource directory structure:




main.xml contains:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<EditText android:id="@+id/text01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Enter the String that is to be Encoded"/>

<Button android:id="@+id/Encode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Encode String"/>

 <Button android:id="@+id/Decode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Decode"/>
</LinearLayout>


Encode QR Code

On click of Encode button we will write the code for generating QR image:


text=(EditText)findViewById(R.id.text01);

        ((Button)findViewById(R.id.Encode)).setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				//pg=ProgressDialog.show(QrcodeActivity.this, null, "Generating...");
				encode_string=text.getText().toString();
				generateQRImage(QrcodeActivity.this, handler, encode_string);
			}
		};

public static void generateQRImage(Activity activity, Handler handler, String value){
		  Intent intent=new Intent();
		  intent.setAction(Intents.Encode.ACTION);
		  intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
		  intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
		  intent.putExtra(Intents.Encode.DATA, value);
		  generateImage(activity, intent, handler);
	}

    public static void generateImage(Activity activity, Intent intent, Handler handler){
		try{

            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(activity, intent);

            activity.setTitle(activity.getString(R.string.app_name) + " - " + qrCodeEncoder.getTitle());

            qrCodeEncoder.requestBarcode(handler, 230);

        } catch (IllegalArgumentException e) {
        	//HelperApp.dismissProgressDialog();
            //showErrorMessage(R.string.msg_encode_contents_failed, "Error",activity);
        }
	}


To generate the QR code image, we send the handler. In handler, we received the message if QR code generation is successful or not. If it is successful then, it sends the QR image as a Bitmap in msg.obj

private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message message) {

			switch (message.what) {
		     	case R.id.encode_succeeded:
		          Bitmap image = (Bitmap) message.obj;
		          if(pg!=null) pg.dismiss();
		          setContentView(R.layout.qr_image);
		          ImageView img=(ImageView)findViewById(R.id.qr);
		          System.out.println();
		          img.setImageBitmap(image);

		        		     	case R.id.encode_failed:
		     	  if(pg!=null) pg.dismiss();

		          break;
			}
		}
	};


We will be setting this image in our own layout
i.e (layout/qr_image.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout android:id="@+id/layout01"
  	android:layout_width="wrap_content"
  	android:layout_height="wrap_content"
  	android:orientation="horizontal"
  	android:layout_centerHorizontal="true"
  	android:layout_marginTop="20dp">
	  <ImageView android:id="@+id/qr"
	  	android:layout_width="200dp"
	  	android:layout_height="200dp"
	  	android:layout_marginLeft="30dp"
	  	android:layout_marginTop="30dp"/>
	  	</LinearLayout>
</RelativeLayout>


Decode QR Code or Barcode

On click of Decode button

((Button)findViewById(R.id.Decode)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				startActivityForResult(intent, 0);

			}

        });

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
 	   if (requestCode == 0) {
 		   //Handle successful scan
 		   if (resultCode == RESULT_OK) {
 	         String contents = intent.getStringExtra("SCAN_RESULT");
 	         String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
 	        // Bitmap barcode=(Bitmap)intent.getParcelableExtra(Intents.Scan.BITMAP);
 	         setContentView(R.layout.result);
 	         ((TextView)findViewById(R.id.content)).setText("Content: "+contents);
 	         ((TextView)findViewById(R.id.format)).setText("Format: "+format);
 	         //((ImageView)findViewById(R.id.image_bitmap)).setImageBitmap(barcode);
 	      } else if (resultCode == RESULT_CANCELED) {
 	    	    //Handle cancel
 		         TextView textView=new TextView(this);
 		         textView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
 		         textView.setText("Failed");
 		         setContentView(textView);
 	      }
 	   }
 	}

Parsing JSON from URL in Android

January 16th, 2012 No comments

Android and JSON

JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.
Remember that some URI’s return a JSONObject object while others return a JSONArray. The following coding uses an URI which returns an JSONArray.

We will be using URL/Web Service:


http://mobisys.in/quicknotify/get_departments.php?company_id=1


We will be getting following JSON:

[{"dept":"Mobile","dept_id":"1"},{"dept":"Web","dept_id":"2"}]


JSON has a reputation for being somewhat hard to read. JSON objects are constructed in a key:value pair format. The object’s elements are separated by commas, and each object is contained within curly braces {}.
An array of objects is contained within square brackets ‘[]‘. This is a common approach to transferring a series of rows from a database to an array of objects in which each array element corresponds to a database row, and each property of the object represents a column of data.

Sample Example

So with this tutorial we will connect to a web service that serves JSON objects/ arrays. We will also learn about how to call Json web service through HttpConnection and send the parameters through GET method of HTTP. We will display the Json array fetched from server in the ListView.

Lets create a project named as”com.mobisys.android.FirstJsonExUrl” having activity
FirstJsonExUrlActivity“.

Firstly main.xml will contain:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    >
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Json"
    android:id="@+id/Button01"
    />
  <ListView
   android:id="@+id/lv"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="8dp"
  />  

</LinearLayout>


& its code after the click will look like:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.Button01)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {

				executeAsyncTask();

			}
        });

    }


Ofcourse, JSON web-service will be called in background thread as it involves HTTP connection. Also, we will use Hashtable to send the GET parameters in URL. Our HelperHttp class will encode the URL and send GET parameters from Hashtable.


private void executeAsyncTask(){
		  Hashtable<String,String> ht=new Hashtable<String,String>();
		  GetDeptAyncTask async=new GetDeptAyncTask();
		  ht.put("company_id", "1");
		  Hashtable[] ht_array={ht};
		  async.execute(ht_array);
		 }

private class GetDeptAyncTask extends AsyncTask<Hashtable<String,String>,Void,String>{

		  @Override
		  protected String doInBackground(Hashtable<String,String>... params) {
		   Hashtable ht=params[0];

		   String json=HelperHttp.getJSONResponseFromURL(BaseUrl+"get_departments.php", ht);
		   if(json!=null) parseJsonString(deptList,json);
		   else{
		    return "Invalid Company Id";
		   }
		   return "SUCCESS";
		  }

		  protected void parseJsonString(ArrayList<DEPT_HOLD> deptList,String json){
			  try {
				   JSONArray array=new JSONArray(json);
				   for(int i=0;i<array.length();i++){
				    JSONObject j=array.getJSONObject(i);
				    DEPT_HOLD d=new DEPT_HOLD();
				    d.dept=j.optString("dept","");
				    d.dept_id=j.optString("dept_id","");
				    deptList.add(d);
				   }

				  } catch (JSONException e) {
				   e.printStackTrace();
				  }

		  } 

		  @Override
		  protected void onPostExecute(String result){

			  if(result=="SUCCESS")
			  {
			   Toast.makeText(FirstJsonExUrlActivity.this, "Success", Toast.LENGTH_SHORT).show();
			   DeptArrayAdapter adapter=new DeptArrayAdapter(FirstJsonExUrlActivity.this,R.id.text1,deptList);
			   ListView listv=(ListView)findViewById(R.id.lv);
			   listv.setAdapter(adapter);
			  }
			  else{}
		  }

		 }


Parsing JsonArray

To parse String into JsonArray we can have:

JSONArray array=new JSONArray(JString);


Extracting the content from JsonObject

Create the JSONObject and extract content using method getJSONObject().

JSONObject j;
j=array.getJSONObject(Jstring);


We can extract its attributes using methods optString()/getString()
optString(): Returns the value mapped by name if it exists. Returns the empty string if no such mapping exists.

getString(): Returns the value mapped by name if it exists

DEPT_HOLD d=new DEPT_HOLD();
d.dept=j.optString("dept","");
d.dept_id=j.optString("dept_id","");



Run the application


Download the source code and APK file

For simplicity we have only mentioned JSON related source code in blog. But if you interested you can download the source code and you can also learn about how to connect to web service through HTTPConnection.

Click here to download the source code

Also you can download APK file
Click here

Android Design Guidelines.

January 15th, 2012 No comments


Android has now come up with design guidelines. Android has launched a new website to help developers improve the look of applications for Android.

Many Android developers will be happy to have this new guidelines :-) .

Categories: Android Tags: , ,