Sunday, 5 May 2013

Android Wrap_content And Match_parent

In Android, while designing layout you always put either "wrap_content" or "match_parenton component’s attribute on "layout_width" and "layout_height",  did any one know what’s the different?

  1. wrap_content – The component just want to display big enough to enclose its content only.
  2. fill_parent – The component want to display as big as its parent, and fill in the remaining spaces. (renamed match_parent in API Level 8)

1. wrap_content

A button component, set "wrap_content" on both width and height attribute. It tell Android to display the button big enough to enclose it’s content “Button Hello World” only.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>





2. match_parent – width

Change the "layout_width" to "match_parent", now, the button’s width will fill in the remaining spaces, just as big as it’s parent "Linearlayout", but button’s height is still big enough to enclose it’s content only.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>





3. match_parent – height

Change the "layout_height" to "match_parent", now, the button’s height will fill in the remaining spaces, just as big as it’s parent "Linearlayout", but button’s width is still big enough to enclose it’s content only.


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

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>




4. match_parent – width, height

Change the both "layout_widthand "layout_height" to "match_parent", the button will display as big as the whole device screen, it just fill in the entire screen space.

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

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>


References

Sunday, 14 April 2013

Android Life Cycle


Android Activity Lifecycle Example Code Description
Here we will learn complete details about an Android Activity Lifecycle Example with details Code Description. Here we will learn details about all real time scenarios and different states of an Android Activity. Once you download the sample code example from here, then you can find line by line code description for an Android Activity. If you are new to Android Activity, then you might like to read my article Android Fundamentals and Components. Anyway lets have a quick reminder on Android Activity Lifecycle. Below image will give us a overall idea about an Activity’s complete LifeCycle, then we will implement all details in our example.




Android Activity states

onCreate()

onCreat Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by onStart().

onRestart()

onRestart Called after your activity has been stopped, prior to it being started again.
Always followed by onStart()

onStart()

Called when the activity is becoming visible to the user.
Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

onResume()

Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.

Always followed by onPause().

onPause()

onPause Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

onStop()

onStop Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.

Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

onDestroy()

The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with theisFinishing() method.

ActivityLifeCycle Example code :-


package com.learnsimply.activitylifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class ActivityLifeCycle extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(this,"onCreate", Toast.LENGTH_SHORT).show();
}

public void onStart() {
super.onStart();
Toast.makeText(this,"onStart.", Toast.LENGTH_SHORT).show();
}

public void onRestart() {
super.onRestart();
Toast.makeText(this,"onRestart.", Toast.LENGTH_SHORT).show();
}

public void onResume() {
super.onResume();
Toast.makeText(this,"onResume.", Toast.LENGTH_SHORT).show();
}

public void onPause() {
super.onPause();
Toast.makeText(this,"onPause.", Toast.LENGTH_SHORT).show();
}

public void onStop() {
super.onStop();
Toast.makeText(this,"onStop.", Toast.LENGTH_SHORT).show();
}

public void onDestroy() {
super.onStop();
Toast.makeText(this,"onDestroy.", Toast.LENGTH_SHORT).show();
}

}






Saturday, 13 April 2013


What is Android Activity ?

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows
  • The basis of android applications
  • A single Activity defines a single viewable screen
  • Can have multiple per application
  • Each is a separate entity
  • They have a structured life cycle
  • Different events in their life happen either via the user touching buttons or programmatically

The user interface of an application is displayed on a device through an Activity, typically with one Activity created for each unique screen. Internally there is a stack of Activities, when moving from one screen to another, the next Activity to be visible is pushed onto the top of the stack – put another way, the Activity on the top of the stack is what is visible on the display. Activities are popped from the stack by pressing the back button, which resumes the previous Activity.

Activity Class

When you want to create a new Activity, you extend the Activity class. The code below shows a simple starting point:

package com.learnsimply.basicactivity;

import android.app.Activity;
import android.os.Bundle;

public class BasicActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
}


Once created you’ll need to associate a layout of the UI for the Activity. The recommended approach is to use an XML-based layout. For example, the layout below shows how you might define a simple table.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">
    <TableRow>
        <TextView
            android:text="@string/row1a"/>
        <TextView
            android:text="@string/row1b"
            android:gravity="right"/>
    </TableRow>
    <TableRow>
        <TextView
            android:text="@string/row2a"/>
        <TextView
            android:text="@string/row2b"
            android:gravity="right"/>
    </TableRow>
</TableLayout>



Let’s assume the layout about was created/saved in a file main.xml. Behind the scenes, the Eclipse plugin will update the R.java file and make a reference to the layout resources defined in main.xml. As an example:



package com.learnsimply.basicactivity;
 
public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040004;
        public static final int row1a=0x7f040000;
        public static final int row1b=0x7f040001;
        public static final int row2a=0x7f040002;
        public static final int row2b=0x7f040003;
    }
}

Notice the reference to main in the layout class. We can now update the BasicTable class defined above, which extended the Activity class, to tie the layout (table) to the Activity we defined, 
we do this be calling the setContentView() method inside onCreate():
package com.learnsimply.basicactivity;
 
import android.app.Activity;
import android.os.Bundle;
 
public class BasicActivity extends Activity 
{
  WebView webView;
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
 
    // Associate table layout to this Activity
    setContentView(R.layout.main);
}
}
Android Manifest
For each Activity, there needs to be an entry in the AndroidManifest.xml file,where you can define a theme,label,permissions, etc.
Here is a sample manifest with one Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.tabletest.table"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TableActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>
</manifest>

Sunday, 31 March 2013

Project Components

src – your source code
gen – auto-generated code (usually just R.java)
libs - Included  libraries
Resources
Drawables (like .png images)
Layouts
Values (like strings)
Manifest file

SRC(Contains Source Code)
In Android Development the src folder is where all you put your main Java code
EX. MainActivity.Java


XML

Used to define some of the resources
Layouts (UI)
Strings
Manifest file
Shouldn’t usually have to edit it directly, Eclipse can do that for you
Preferred way of creating UIs
Separates the description of the layout from any actual code that controls it
Can easily take a UI from one platform to another



R Class

Auto-generated: you shouldn’t edit it
Contains IDs of the project resources
Enforces good software engineering
Use findViewById and Resources object to get access to the resources
Ex. Button b = (Button)findViewById(R.id.button1)
Ex. getResources().getString(R.string.hello));


 Layout

Eclipse has a great UI creator
Generates the XML for you
Composed of View objects
Can be specified for portrait and landscape mode
Use same file name, so can make completely different UIs for the orientations without modifying any code.


Strings

 In res/values
strings.xml
Application wide available strings
Promotes good software engineering
UI components made in the UI editor should have text defined in strings.xml
Strings are just one kind of ‘Value’ there are many others

Menifest File

Contains characteristics about your application
When have more than one Activity in app, NEED to specify it in manifest file
Go to graphical view of the manifest file
Add an Activity in the bottom right
Browse for the name of the activity
Need to specify Services and other components too
Also important to define permissions and external libraries, like Google Maps API

Drawables

A Drawable resource is a general concept for a graphic which can be drawn. The simplest case is a graphical file, which would be represented in Android via a BitmapDrawable class. Bitmaps are typically stored in one of theres/drawable folders. The Android project creation wizard creates several of these folders by default, you can provide different sized files for different resolutions of Android devices. If you only provide one file for all sizes the Android system will scale the resource.

In additional to graphical files, Android supports XML drawables and 9-patch graphics. XML drawables are used to describe shapes (color, border, gradient), State and Transitions and more.
9-patch graphics are used to define which part of a graphic should be stretched if the View which uses this graphic is larger than the graphic.

Libs

The /lib folder is used to import library files in project that executables make use of and also you can import third party library files .