Sunteți pe pagina 1din 52

DURGA SOFT SOLUTIONS

ANDROID

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 1


ANDROID:

What is Android?

 Android Is a mobile Operating System developed by Google.

 Android Os is based on open Linux kernal.


 Unlike iPhone Os, Android Os is Open source, meaning the developers can modify and
customize the os for each phone.
 Developers can create programs for Android by using the Android SDK(Software
Development Kit).
 Android programs are written in java and run through Google’s Davlik virtual machine,
which optimized for mobile devices.

Android Architecture :

The Main Components in the Android Architecture are

1. Android Application

2. Application Framework

3. Libraries(Core & Native)

4. Runtime Android (DVM- Dalvik Virtual Machine)

5. Kernel – Linux

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 2


1. Android Applications:

These are applications written in Java. Some of basic applications includes


an calendar, email client, SMS program, maps, making phone calls, accessing the Web browser,
accessing your contacts list and others.

2. Application FrameWork:

This is the skeleton or framework which all android developers has to follow. The
developers can access all framework APIs an manage phone’s basic functions like resource
allocation, switching between processes or programs, telephone applications, and keeping track of
the phone’s physical location.

3. Libraries:

a. Core Libraries: The Android runtime layer which includes set of core java libraries and
DVM (Dalvik Virtual Machine) is also located in same layer.

b. Native Libraries: This layer consists of Android libraries written in C, C++, and used by
various system. These libraries tells the device how to handle different kinds of data and are
exposed to Android developers via Android Application framework. Some of these libraries
includes media , graphics, 3d,SQLite,web browser library etc.

4. Runtime Android (Dalvik virtual Machine):

This layer includes set of base libraries that are required for java libraries. Every Android
application gets its own instance of Dalvik virtual machine. Dalvik has been written so that a device
can run multiple VMs efficiently and it executes files in executable (.Dex) optimized for minimum
memory.

5. Kernel – Linux:

This layer includes Android’s memory management programs, security settings, power
management software and several drivers for hardware , file system access, networking and inter-
process-communication. The kernel also acts as an abstraction layer between hardware and the
rest of the software stack.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 3


Android Versions:

 First Major
Android version
1.0 (API level 1) of Android is 1.5 (CupCake)
 may 2009
Android 2.3.3–2.3.7 Gingerbread (API level 10)

 Android
Android 1.11.6
(API(Donut)
level 2)  Android 3.0 Honeycomb (API level 11)

 Android
Android 1.52.1(Éclair)
Cupcake (API level 3)  Android 3.1 Honeycomb (API level 12)

 Android
Android 1.62.2(Froyo)
Donut (API level 4)  Android 3.2 Honeycomb (API level 13)

 Android
Android 2.02.3,2.3.2,2.3.3,….(GingarBread)
Eclair (API level 5)  Android 4.0–4.0.2 Ice Cream Sandwich (API level 14)

 Android
Android 2.0.1 Eclair (API level 6) 
3.1,3.2,3.2.1,3.2.2,3.2.3….(HoneyComb) Android 4.0.3–4.0.4 Ice Cream Sandwich (API level 15)

 Android
Android 2.14.0(ice Cream
Eclair (API level 7)Sandwitch)  Android 4.1 Jelly Bean (API level 16)

 Android 2.2–2.2.3 Froyo (API level 8)  Android 4.2 Jelly Bean (API level 17)

 Android 2.3–2.3.2 Gingerbread (API level 9)  Android 4.3 Jelly Bean (API level 18)

 Android 2.3.3–2.3.7 Gingerbread (API level 10)  Android 4.4 KitKat (API level 19)

 2.11 Android 3.0 Honeycomb (API level 11)

Android
 2.12Features:
Android 3.1 Honeycomb (API level 12)

 2.13 Android 3.2 Honeycomb (API level 13)


The following are the advantages of Android
 2.14 Android 4.0–4.0.2 Ice Cream Sandwich (API

Application
 level 14) framework enabling reuse and replacement of components
 2.15 Android 4.0.3–4.0.4 Ice Cream Sandwich (API
 Dalvik virtual machine optimized for mobile devices
level 15)

 2.16
Optimized graphics
Android 4.1 Jelly Bean (API level 16)

 2.17 Android 4.2 Jelly Bean (API level 17)


 SQLite for structured data storage
 2.18 Android 4.3 Jelly Bean (API level 18)

 2.19
Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC,
Android 4.4 KitKat (API level 19)

AMR, JPG, PNG, GIF)

 GSM Telephony (hardware dependent),Bluetooth, EDGE, 3G, and WiFi (hardware


dependent),Camera, GPS, compass, and accelerometer (hardware dependent)

 Rich development environment

To Create , Test and build Android applications we need the following Softwares:

1. Eclipse IDE (is optional can use any other tool. But Eclipse is recommended ) + added with
Android Development plugin

2. Android SDK(Software Development Kit

we can download these s/w from this site http://www.android.com

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 4


Required Softwares:

 The android app can be developed on any OS such as Windows, Linux, and MAC Os

The following are the resources that are required to set up into the system for android
application development

1. An IDE (Integrated Development Environment) : The Eclipse is the most prefered IDE. We
can download the Eclipse IDE from

the following website. http://www.eclipse.org

2. Add a plugin making the eclipse aware of Android.

The Android Development Tool(ADT) is the Eclipse plugin doing this. For this we want to
use the Install plugin option of the Eclipse IDE.

Alternatively we can get the ADT zip file downloaded from http://www.android.com and
manually copy the features and plugins folders into the eclipse root folder , which we got
extracting the ADT zip file.

3. In addition to the IDE and its plugin simplifying creating the android applications we want
to have an android SDK for building, and testing the android applications, we can download
the SDK from http://www.android.com After extracting the downloaded zip file for the SDK
we need to run the ‘SDK Manager’ whicj is found in the <android-sdk-home> this find &
install various available packages.

The Android Application:

The Android Application is basically composed of the following 3 type of components.

1. Activity

2. Service

3. BroadCast Receiver

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 5


Activity:

 The Activity is the one of the core components of Android App

 This is crated as a Java Object subtype ofandroid.app.Activity

 This component is managed by the Android App Framework

 The Following are the possible methods that we can override the Activity Object.

The onCreate() :

The onCreate() methos is used to implement initialization code like presenting the View for
the Activity.

The onStart():

The onStart() method allows writing the code executing on getting the activity foreground

The onRestart() :

The onRestart() method can initialize the resources that are closed in the onStop().

The onStop() :

The onStop() method can use the resources that are not required on paused activity. This
may even required to solve the start of the activity.

The onResume() :

The onResume() can create the resources and / or get the saved state of the activity to get
into foreground.

The onDestroy() : The onDestroy() can perform the finilizations for the activity.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 6


The Life Cycle of Activity is:

Or

Creating an Activity:

While creating/starting the activity the following methods are invoked.

 onCreate()

onStart()

onResume()

Some other Activity wants to come to ForeGround:

At this stage ‘onPause()’ of this activity is invoked and then the other activity is
started. In case of the other activity is taking the complete screen the ‘onScreen()’ is invoked
getting the activity to background(stopped). Otherwise it gets paused.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 7


The Activity is getting into the ‘foreground’:

This activity which is paused or stopped because of some other activity is foreground, is
now coming foreground because of the existing foreground activity is destroyed.

At this stage the ‘onResume()’ is the only method invoked in case of getting from paused.

If it was stopped the following methods are invoked.

 onRestart()

onStart()

onResume()

The Activity Destroying:

The Activity while destroying from foreground invokes the following methods.

onPause()

onStop()

onDestroy()

Point to Note : The android system can destroy the stopped activity without a user request, just
invoking ‘onDestroy()’

The Startup Application :

For the first time want to take the following points to check

 Install with Android SDK with necessary APIs


 Create a ‘AVD(Android Virtual Device)’, we can do this using ‘SDK Manager’ which
you find in the Android SDK installed.
 Eclipse is installed with ADT Plugin, and for the first time we want to set the
Android SDK location in Eclipse-window- Preferences.
 Select ‘Android’ from the left side tree.
 Browse the Android SDK Install Folder
 Eg: d:\android\SDK-windows
By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 8
Once Creating the Android project we find the project is created with one activity bydefault.

The following are the few important documents or folders to observe.


When you create a new Android project, you get several items in the project's root
directory:

 src
A folder that holds the Java source code
 gen
This is where Android's build tools will place source code that they generate.
R.java" is a generated class which contains the text and the UI elements.
Android projects come with this free class 'R' which is short for Resource.
This is an automatically generated class that we can use to reference
resources in our project. We should not try to modify this class manually.
 assets
A folder that holds other static files you wish packaged with the application
for deployment onto the device.
 bin
In Eclipse, the ADT plugin incrementally builds our project as we make
changes to the source code. Eclipse outputs an .apk file automatically to the
bin folder of the project, so we do not have to do anything extra to generate
the .apk.
 res
A folder that holds resources such as icons, graphic user interface (GUI)
layouts, etc. that are packaged with the compiled Java in the application.
 AndroidMainFest.xml
An XML file describing the application being built and which components
(activities, services, and so on) are being supplied by the application. This file
is the foundation for any Android application. This is where you declare what
is inside your application. You also indicate how these pieces attach
themselves to the overall Android systems; for example, you can indicate
which activity or activities should appear on the device's main menu (a.k.a.
the launcher).
When you create your application, a starter manifest will be generated for
you automatically. For a simple application, offering a single activity and
nothing else, the auto generated manifest will probably work out fine, or
perhaps require a few minor modifications. But on the other spectrum, the
manifest file for the Android API demo suite is more that 1,000 lines long.
Your production applications will probably falls somewhere in the middle.
Most of the manifest will be describes detail in later chapters.
 project.properties
By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad
Property files used by. the
www.durgasoft.com
Ant build script. 9
Creating an Activity:

 The activity class needs to be a subtype of android.app.Activity


 The onCreate() method is one basic method which minimum we want to override .
Like we may want to create / locate the View and set it to the Activity.

The following methods of Activity are used to set the View


o setContentView(View)
o setContentView(int)

The first allows to set the View Object may be created in the program here. And the
later allows setting the view defined in the XML document.

The FirstActivity.java :

package com.durgasoft.android;

import com.durgasoft.android.R;

import ………….;

public class FirstActivity extends Activity {

/** Called when the activity is first created. */ OUT PUT SCREEN
@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Code without main.xml

/* TextView tv=new TextView(this);

tv.setText("Hello from FirstActivity");

setContentView(tv);

*/

// Code with main.xml

setContentView(R.layout.main);

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 10


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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
>
</TextView>
</LinearLayout>

The android application includes a generated resource file named ‘R’ which lists all the resources
defined with unique identity. And this xml View is also given with a unique id to refer in the
program. The id can be accessed using ‘R.layout.Main’.

Thus the activity can have this View set as shown below

public class FirstActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

 It is found in most cases creating a complex view it is convenient to go for XML style
 How ever we can get View created in xml into the activity and do necessary changes .

Example:

Public void onCreate(………){

setContentView(R.layout.main);

TextView tv=(TextView)findViewById(R.id.tv1);

Tv.setText(“New Text”); }

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 11


To run the above code could give an error as in the main.xml file the TextView is not
specified with any id. To run this above code successfully add the following attribute into
the <TextView> Tag.

andrioid:id=”@+id/tv1”

 The ‘+’ in the value of the attribute describes add the is resource into the ‘R’ file if
not available
 The android application support multiple type of resource such as layouts, ids and
Strings
 The String resource is can be added into ‘strings.xml’ file res/values folder
Eg:
<resource>
<String name=”text”> Text String Message </String>
</resource>
 These resources are added into the R file for convenient access.
 To access the resources in ‘xml’ documents we use the following syntax.

Syntax: @<type>/<name>
Eg: @String/test

In case the same is required to access in the program we use.

R.<type>.<name>

We can use the following method for getting the string resource declared in the xml.

String s1=getResources().getString(R.String.test);

Similar to String we can have a Boolean resource .this is declared using <bool> tag.

Starting an Activity:
 The activity with ACTION_MAIN, and CATEGORY_LAUNCHER is main activity to run
on accessing the application.
 In addition we may want to start another activity from such main activity.
 We use startActivity(Intent) method of the Activity to do this.

The Intent Object:


 The Intent is a value object describing a message to the android system to perform
an action.
 Like we may want to describe the android system to start an activity or background
service
 The Intent Object describes following six methods

1. Component Name 4. Data


2. Action 5. Extras
3. Categories 6. Flags

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 12


The Intents are of two types.

1. Explicit Intents
2. Implicit Intents

Explicit Intents:

These type of intents are started with component name, which


directly locates a Activity by its name.

Example: Lets add a new activity in the previous class

Public class Activity2 extends Activity

Public void onCreate(Bundle b)

super.onCreate(b);

setContentView(R.layout.main1.xml);

This new Activity is requited to register into the AndroidManifest.xml

<activity android:name=”.Activity2” android:label=”Activity2”></activity>

In the existing Activity:

Lets consider the main.xml is the layout document and has the following tag.

<Button

………………………………….

Android:onClick=”myMethod”/>
The following method needs to added into the existence Activity

public void myMethod(View view)

Intent i=new Intent();

i.setComponentName(new ComponentName(getApplicationContext(),Activity2.class));

startActivity(i); }

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 13


Implicit Intents:
 Although the explicit intents are simple but are useful only to locate the activities whose
names are known to us, which is generally with the activities of our application.
 In case if we want to access the activities of some other applications in the system explicit
would not meet our requirement
 In this case the android system is responsible to find the suitable activities to handle this
intent. In case if none found the ActivityNotFoundException would be thrown.
 To do this the intent object is matched with the configured intent filter for the activities .The
following tag is used in the <activity> tag to configure the intent filter.

<intent- filter>........................</>

Implicit Intent:
 In Case if the Intent without a component is given , the f/w needs to use the
package manager conduct the following 3 tests to find the suitable activities
that can handle this intent.
o Action:
 Here the intent action is match with the actions of the intent
filters of the activities.
 If the intent doesn’t has an action(ies it is null) in such case
every activity with an intent filter atleast with one action will
passes this test.
 Android includes multiple builtin actions such as ACTION_CALL
 We can create our own action, It is recommended to use package
name as prefix for the action name. For example
com.durgasoft.android.GAME_START
o Data:
 Once if the activity passes the action test then it is checked for
data test. Here the MIME type and / or path is matched to find is
the activity matching to handle the intent with the given data.
o Category:
 The intent and intent filter can have multiple categories added.
 All the categories describes in the intent should match the
intent filter categories passing this test.

Note:

The category ‘android.intent.category.DEFAULT’ is mandatory to include into the


intent filter to have any implicit intents locating this activity.

This is excempttion for LAUNCHER activity.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 14


Intent and Intent Filters:
 The intent filters for an activity are declared in the android manifest.xml file
as part of configuring the activity.
 The <intent-filter> can have <action>,<data> and <category>

Note:

 Having at least one <action> is mandatory to choose this activity using


implicit intent
 Having the <category> with the namae android.intent.category.DEFAULT is
also mandatory for locating using implicit intents. Example for the
LAUNCHER and ALTERNATIVE category intent.
 The implicit intents requires to identify the appropriate activity to handle
the intent.
 To do this it matches the intent info(such as action, type, data, and category)
with the intent filters info of the activity.
 If the intent info matches with the intent filter info then the enclosing
activity is chosen to handle this intent

Example

Intent i=new Intent();

i.setAction(Intent.ACTION_DIAL);

startActivity(i);

This starts a phone dialer activity allowing us to dial the number and make a call.

Intent i=new Intent();

i.setAction(Intent.ACTION_DIAL);

Uri.Builder u=new Uri.Builder();

u.scheme(“tel”);

u.path(“1234567890”);

i.setData(u.build());

startActivity(i);

 This starts the phone dialer activity with the number ‘1234567890’ entered
directly to make a call.
 Alternative to ACTION_DIAL we can use ACTION_CALL for directly making a
call.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 15


Intent i=new Intent();
i.setAction(Intent.ACTION_GET_CONTENT);
Uri.Builder u=Uri.Builder();
u.scheme(“content”);
u.path(“/contact”);
i.setData(u.build());

 In addition to ‘startActivity()’ we can use the ‘startActivityForResult()’ method to


start an activity.
 The ‘start ActivityForResult ()’ method is used to start an activity that can carry
some data returning to the parent activity.

This method takes 2 arguments.


First Arg: Intent

Second Arg: int(specifies the request code, this is used diffentiate
between the multiple child activities that are possible to start from
the activity)
 This code is used in ‘onActivityResult()’ method to find the result from which child
activity.
 The child Activity can use the following method for sending the result.

setResult(int resultcode,Intent data)

 Once the childActivity is finished then the following method of the parent activity is
invoked.
onActivityResult(int requestcode,int resultcode,Intent data)

Note:

In Case if the child activity finished without setting the result , the data will be null.

Sample Program on Intents:

SecondActiivity.java:

package com.durgasoft.android;

import com.durgasoft.android.R;

import .................................................................;

public class SecondActivity extends Activity {

/** Called when the activity is first created. */

@Override

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 16


public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// Code for explicit Intents

public void MyMethod(View view)

Intent i=new Intent();

// Register the Activity2 class in the android manifest.xml file inside <application> tag

// <activity android:name=".Acitivity2"></activity>

i.setComponent(new ComponentName(getApplicationContext(),Activity2.class));

startActivity(i);

// Code for implicit Intents

public void MyMethod1(View view)

Intent i=new Intent();

i.setAction(Intent.ACTION_DIAL);

startActivity(i);

Activity2.java

package com.durgasoft.android;

import --------------------------------------------;

public class Activity2 extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main1); } }

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 17


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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" ></TextView>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:onClick="MyMethod"
android:text="Explicit Intent"></Button>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:onClick="MyMethod1"
android:text="Implicit Intent" ></Button>

</LinearLayout>

Main1.xml

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


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

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is a Second Activity"

></TextView>

</LinearLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 18


AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.durgasoft.android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />

<application android:icon="@drawable/icon" android:label="@string/app_name">


<activity android:name=".SecondActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity2"></activity>

</application>

</manifest>

Understanding the Views:


 The Userinterface of an activity is defined using a View Object.
 The View group is one special View type that allows us compose multiple View’s
into a single view, thus we can have multiple views to present in a single screen (ies
a single View).
 The following method of an Activity is used to set the View for this Activity.

setContentView(android.View.View)
setContentView(int ViewID)

 The View can be described in two styles.


o Into XML declarative
o In Activity( Java Code) programmatic.
We can use both in combination.

 It is recommended use XML style , which can simplify creating the View and allows
take the advantage of first design using click and drag supported by the IDE.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 19


Usign XML Style:

 In this case we create an XML documents into

res/layouts folder

 An XML document can describe only one View. Note the View here can be a
View group thus a tree of Views
 Here we have an XML tag one for each concrete View type to use defining the
View.

Example:
<Button...../>

<TextView......../>

<EditView....../>

Example:

<!--Simple Button.xml-->

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text=”Click Me Boss”
android:onClick=”Submit” />

 To set this view as User Interface for the Activity we can have the following
code in the ‘onCreate()’ method of the activity.
setContentView(R.layout.simpleButton);

Note:

The android XML file names cannot have uppercase and special and white
space characters.

 If we want have multiple view components into a UI we shall work with


ViewGroup such as Layouts.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 20


The Linear Layout:
 This supports arranging multiple View components one after the other
Vertical/Horizontal.
 The Orientation property of this component specifies is the child View
components to arrange in Vertical/Horizontal.
 If vertical – only one View component is allowed with each row.
 If Horizontal- All the Views are arranged into a single row.

Example:

<!-- simple_linear_layout1.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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="---------------------Linear Layout-------------------"
android:textStyle="bold"></TextView>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="A"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="C"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="D"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="E"></TextView>
</LinearLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 21


The Table Layout:

 Is a subtype of LinearLayout
 This supports arranging set of table row objects into the Layout. A Table Row
Object supports adding one or more Views including specifying column
index.

Example:
<!-- table_layout_View1.xml-->

<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow >
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="F"></TextView>
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="G"></TextView>
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="H" > </TextView>
</TableRow>
<TableRow >
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="I" ></TextView>
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="J" ></TextView>
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="K"></TextView>
</TableRow>
</TableLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 22


 The Table layout can have multiple table rows and the View’s describes
into the Table Row are added to the row in the same order they appear.
 We can programmatically add rows to the layout.

Example:

In onCreate() method:

TableRow tr=new TableRow(this);

TextView tv1=new TextView(this);


tv1.setText("L");

TextView tv2=new TextView(this);


tv2.setText("M");

TextView tv3=new TextView(this);


tv3.setText("N");

tr.addView(tv1);
tr.addView(tv2);
tr.addView(tv3);

TableLayout tl=(TableLayout)findViewById(R.id.table1);
tl.addView(tr);

In the table_layout while describing the views in the TableRow, we can


use android:layout_column attribute to specifying the column index this
view has to set into

Note :
The column index starts with 0.

We can use the following method to collapse thee expanded column.


(ies shown/hide the column)

setColumnCollapsed(int colIndex,Boolean flag)

Note:
The column index starts with ‘0’

We can get the views and resource the views from the table
layout using the method as described below.
getChildAt(int rowindex)
removeView(View)

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 23


sample program on Table Layout and LinearLayout:

ThirdActivity.java:

package com.durgasoft.android;
import com.durgasoft.android.R;

import .........................................................................;

public class ThirdActivity extends Activity {


/** Called when the activity is first created. */
@Override

// Example for linear layout and table layout


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

TableRow tr=new TableRow(this);

TextView tv1=new TextView(this);


tv1.setText("L");

TextView tv2=new TextView(this);


tv2.setText("M");

TextView tv3=new TextView(this);


tv3.setText("N");

tr.addView(tv1);
tr.addView(tv2);
tr.addView(tv3);

TableLayout tl=(TableLayout)findViewById(R.id.table1);
tl.addView(tr);

public void Table(View view)


{
TableLayout tl=(TableLayout)findViewById(R.id.table1);
tl.setColumnCollapsed(0,true);
}
}

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 24


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" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="---------------------Linear Layout-------------------"
android:textStyle="bold"></TextView>

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="A" ></TextView>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B" ></TextView>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="C" ></TextView>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="D" ></TextView>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="E" ></TextView>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="---------------------Table Layout-------------------"
android:textStyle="bold" ></TextView>
<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow >

<TextView android:layout_width="100px"
android:layout_height="wrap_content"
android:text="F" ></TextView>
<TextView android:layout_width="100px"
android:layout_height="wrap_content"
android:text="G" ></TextView>
<TextView android:layout_width="100px"
android:layout_height="wrap_content"
android:text="H" >
</TextView>

</TableRow>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 25


<TableRow >

<TextView android:layout_width="100px"
android:layout_height="wrap_content"
android:text="I" ></TextView>
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="J" ></TextView>
<TextView android:layout_width="100px"
android:layout_height="wrap_content"
android:text="K" >
</TextView>
</TableRow>

</TableLayout>

<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow >

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="-----------------Table Row using Prog--------------"
android:textStyle="bold" ></TextView>
</TableRow>

</TableLayout>

<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/table1" ></TableLayout>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click Me Boss"
android:onClick="Table" ></Button>

</LinearLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 26


The Button:
 We use the android.View.Button class to create this
component. Or <Button> tag in the XML document.
Example:
Button b=new Button(this);
b.setText(“Submit”);

In XML:
<Button android:text=”Submit”/>

Configuring the Button to listen for Click event:

Programatic:

 In Case we use the following method of Button to set the listener for
onClick event.
setOnClickListener(View.onClickListener)
 The View.OnClickListener is an interface that declares only one
method.
public void onClick(View v)
 This method is invoked by the View component when a user clicks
the component.
 We can create a class implementing this interface . most of the time
we prepare creating an anonymous class

Example:

Button b1=new Button(this);


OnClickListener l=new OnClickListener(){
public void onClick(View v)
{
...........................
};
b1.setOnClickListener(l);

Declarative :
 This is simple ,here we want to use ‘android:onClick’ attribute
specifying the name of the method to listen for this event.
 The method needs to be implemented in the content of this Buutton ,
with the following signature
public void <method-name> (View v)

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 27


The Relative Layout:

 In this case the components in the view can be placed with respect to the
other components in the view or with respect to this layout (ies parent)
view.
 We can use the following attributes to configure the component align with
respect to the layout.
 android:layout_alignParentBottom: specifies whether the component is
to be placed at the bottom of the layout. ‘true’ describes to place to the
Bottom.
 android:layout_alignParentTop
 android:layout_alignParentLeft
 android:layout_alignParentRight
 The following attributes can be used to place the component with respect to
the another components.
 android:layout_below : specifies the id of the component below
which this component has to be arranged.
 android:layout_toLeftOf
 android:layout_toRightOf

Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="Hello This is from Relative Layout"
android:id="@+id/tv1" ></TextView>
<Button android:layout_below="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OnClick"
android:id="@+id/b1" > </Button>
<TextView android:layout_below="@+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is the Activity from Relative Layout"
android:id="@+id/tv2" > </TextView>
<!-- Similarly we have
android:layout_toLeftOf="@+id/b1"
android:layout_toRightOf="@+id/b1"
android:layout_above="@+id/b1"-->
</RelativeLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 28


Sample Program on Relative Layout & Button:

package com.durgasoft.android;

import com.durgasoft.android.R;

import ----------------------------------------------;

public class FourthActivity extends Activity {

// Example for Relative Layout and Buttons

/** Called when the activity is first created. */


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

Button b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

Toast.makeText(getApplicationContext(),"Hi This is From


Button",Toast.LENGTH_LONG).show();

}
});

Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="Hello This is from Relative Layout"
android:id="@+id/tv1"
></TextView>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 29


<Button
android:layout_below="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OnClick"
android:id="@+id/b1"
>
</Button>

<TextView
android:layout_below="@+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is the Activity from Relative Layout"
android:id="@+id/tv2"
>
</TextView>
<!-- Similarly we can have
android:layout_toLeftOf="@+id/b1"
android:layout_toRightOf="@+id/b1"
android:layout_above="@+id/b1"-->

</RelativeLayout>

The EditText:
 This is a text field that allows taking the text content input from the
user.
<EditText............/>

Example:

<LinearLayout..................>
<Button android:onClick=”onClickB1”......./>
<EditText
android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/et1"></EditText>
</LinearLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 30


In The Activity Class:

public void onClickB1(View v)


{
EditText v1=(EditText)findViewById(R.id.v1);
String value=v1.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGH_LONG).show();
}

View ViewGroup
TextView LinearLayout
EditText RelativeLayout
Button TableLayout
ToggleButton FrameLayout
CheckBox ListView
RadioButton ScrollView
Spinner TableView
DatePicker RadioGroup
TimePicker ProgressBar
DigitalTime ImageButton
AnalogTime Image

The TextView autolink option ,this is used to have links automatically created for
the phone numbers , email ids and website address supporting us to click performing
necessary action. We use android:autolink attribute to configure this. This defaults to none,
and we can specify phone, email, web, map, or all.

The AutoCompleteTextView:
 This is a subtype of EditView , this allows us get the help content
listing to choose the values from . we can use the following tag to
declare this component.
<AutoCompleteTextView………………../>

Example:
<AutoCompleteTextView
android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/act1" >
</AutoCompleteTextView>

In the Activity onCreate() method we can have the following code for
describing the autocomplete words.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 31


AutoCompleteTextView act=(AutoCompleteTextView)findViewById(R.id.act1);

String[] str=new
String[]{"SVU","OU","JNTUK","JNTUH","ANDHRA","SKU","YVU","VSU","PALAMURU","MAHA
TMA","OTHER"};

ArrayAdapter< String> aa=new


ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1li
ne,str);

act.setThreshold(1);
act.setAdapter(aa);

The Toggle Button:


 This is a subtype of button , this is a special type similar to the
‘CheckBox’ allowing us present the a view taking data like ‘yes’ or ‘no’
from the user.

We use the following tag to have this view.

<Toggle Button
android:layout_width="150px"
android:layout_height="wrap_content"
android:taxtOn=”yes”
android:textOff=”No”/>

The android:textOn specifies the text to display when this button Check
(ies on) and textOff for content to displaying on unchecked(ies off).

The CheckBox:
 This is also a subtype of button allows us to take checked/unchecked
decisions from the user.
 We use the following tag to declare this view.

<CheckBox
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="@+id/cb1"
android:text="MCA"
android:onClick="CheckBox"></CheckBox>

In the activity class we can have the following method.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 32


public void CheckBox(View view)
{
CheckBox cb1,cb2;

cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);

if(cb1.isChecked())
{
Toast.makeText(getApplicationContext(), "MCA is
Selectd",Toast.LENGTH_LONG).show();
}
else if(cb2.isChecked())
{
Toast.makeText(getApplicationContext(), "BTech is
Selectd",Toast.LENGTH_LONG).show();
}
}

The RadioButton & Radio Group:

 The RadioGroup allows having multiple RadioButtons to choose between


 This allows setting
onCheckedChangeListener()
 Where this listener support only one method
onCheckedChange(RadioGroup, int)

The second arfument described that id of the checked radio button ,


and ‘-1’ in case of the clearing the check of the group.

To make none of the radio button to check we can use clearCheck()


method of RadioGroup.
In XML Document:

<RadioGroup >
<RadioButton android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb1"
android:text="Male"
android:onClick="RadioBox" ></RadioButton>
<RadioButton android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb2"
android:text="Female"
android:onClick="RadioBox" ></RadioButton>
</RadioGroup>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 33


In The Activity Class:

public void RadioBox(View view)


{
RadioButton rb1,rb2;

rb1=(RadioButton)findViewById(R.id.rb1);
rb2=(RadioButton)findViewById(R.id.rb2);

if(rb1.isChecked())
{
Toast.makeText(getApplicationContext(), "male is
Selectd",Toast.LENGTH_LONG).show();
}
else if(rb2.isChecked())
{
Toast.makeText(getApplicationContext(), "Female is
Selectd",Toast.LENGTH_LONG).show();
}
}

The Spinner:
 This is a list box type allowing us to choose between the given values.
 We use the following tag for defining this type of View.

<Spinner
android:layout_width="150px"
android:layout_height="50px"
android:id="@+id/sp1" > </Spinner>

 We can add the String array resources using the following tag.

<String-array name=”myarray”>
<item>Value1</item>
<item>Value2</item>
</String-array>

Now we want to set the values for the spinner we write the following code in
the activity class onCreate() method.

String values[]=getResources.getStringArray(R.array.myarray);
ArrayAdapter<String> aa=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item,values);
Spinner sp1=(Spinner)findViewById(R.id.sp1);
sp1.setAdapter(aa);

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 34


we can add these entries declaratively also using the following attribute

android:entries=”@array/myarray”

We can have a OnItemSelectedListener configured to this component, This supports


the following method.

onItemSelectedListener(AdapterView v,View selectedView, int position,long len)

we use setOnItemSelectedListener(OnItemSelectedListener) method of


Spinner to set this listener.

The Scroll View :

 This allows us define the view with large height like may be with many
components into it.
 We use <ScrollView> tag to describe having the Scroll support.

The ListView:

 This View allows us to have set of values to list.


We use <ListView> tag to define this view.

Example:

Add the following tag in main layout.

<ListView
android:layout_width="150px"
android:layout_height="50px"
android:id=”@+id/mylist”/>

In the ‘onCreate()’ method of the activity we can have the following code for setting
a list of values.

ListView lv=(lv)findViewById(R.id.mylist);
String values[]={“value1”,”value2”};
ArrayAdapter<String> aa=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item,va
lues);
lv.setAdapter(aa);

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 35


The onItemClickListener:

 We can configure this listener to the ‘ListView’ this declares only one
method.

public void onItemClickListener(AdapterView Parent,View v,int position,long id )

we can have a text filtering for the ListView we can be enable using the following
method of the ListView.

setTextFilterEnabled(Boolean)

we can use ListActivity as a utility for creating the Activity that just needs a
ListView as a View.

public class MyActivity extends ListActivity

{
public void onCreate(Bundle b)
{
super.onCreate(b);
ListView lv=getListView();
……………………..
}
}

The GridView:

 This is similar to the ListView , but supports arranging the elements into
rows and columns.
 The following tag is used to define this View.

<GridView ....></>
 We use android:numColumns attribute specifying the number of columns,
and the number of rows is decided decided based on the items.
 Like done with the ListView we set the adapter for the items,and can set
thee ‘OnItemClickListenr’
The DatePicker:

 This allows us to have a view that can take the date from the user. The
following tag is used to configure this view

<DatePicker .........../>

And the ‘init()’ method of the DatePickerDialog is used to set

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 36


the initiated date and the onDateChangedListener.

If the method is not invoked it by default sets the date to the system date.

The TimePicker:

 Similar to the DatePicker this view allows us to select the time that includes
hours and minutes.
 This is alsosupported with a listener to get the notification on the change in
the time, just like with DatePicker, this supports onTimeChangedListener
with one method described below.

void onTimeChanged(TimePicker,int hours,int minutes)

Progress Bar:

 This is the View that supports to describe the end user that some long
process is being taking up and you may want to wait for completing process.
 We generally can categorize the Progress Bar into two types.

1.Indetermine ProgressBar

2. Determine ProgressBar

Indetermine ProgressBar:

In this case the progress bar doesn’t describes the status of the work
completed and/or the balance work, this is used in case if we are not known
like that amount of work is completed and how much still balance.

Determined ProgressBar:

The following tag is used to describe the progress bar, and by default
this is Indeterminent.

<ProgressBar.............../>

We use the setVisibility(int) method to show or make this View


invisible . like may be once the long running work is got completed . we can
make this invisible.

Example:

ProgressBar pb=(ProgressBar)findViewById(R.id.pb);
pb.setVisibility(ProgressBar.GONE);

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 37


we can have this progress bar on the title bar itself . To have this we
want to request for the respective window feature. We use the following
code in the activity before setting the ContentView to do this.

requestWindowFeature(Window.FEATURE_INDETERMINE_PROGRESS)
(before setContentView(.............))

And the following method of the Activity can support us to show the
visibility of this feature.

setProgressBarIndeterminate Visibility(boolean)

Note : This method e want to use after setting the ContentView

 Similarly we have ‘determinate ProgressBar’ also on to the title bar.


For this we want to request for the following window Feature.

requestWindowFeature(Window.FEATURE_PROGRESS);

 And same like earlier we use the following method for setting the
visibility of this view.

setProgressBarVisibility(boolean)

 In addition here we can set the progress using the following method
of activity.

setProgress(int)

 The maximum progress is defined as 10000. Meaning 5000 progress


values describes 50% of progress.

Sample Program on all Views:

FifthActivity.java

package com.durgasoft.android;

import ……………………………………………………;

public class FifthActivity extends Activity {

private static int DATE_PICKER_DIALOG=1;


private static int TIME_PICKER_DIALOG=2;

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 38


/*

Example for All The View ---> EditText,Buttons,


Radio Buttons,CheckBox,Spinners,ToggleButtons,
AutoCompleteTextView,DatePickerDialog,TimePickerDialog
AnalogTime,ScrollView,ProgressBar,ImageButton,ListView,RadioGroup

*/

/** Called when the activity is first created. */


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

AutoCompleteTextView act;
act=(AutoCompleteTextView)findViewById(R.id.act1);

String[] str=new
String[]{"SVU","OU","JNTUK","JNTUH","ANDHRA","SKU","YVU","VSU","PALAMURU","MAHA
TMA","OTHER"};

ArrayAdapter< String> aa=new


ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1l
ine,str);

act.setThreshold(1);
act.setAdapter(aa);

Spinner sp1=(Spinner)findViewById(R.id.sp1);

String[] str1=getResources().getStringArray(R.array.myarray);

ArrayAdapter< String> aa1=new


ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1l
ine,str1);
sp1.setAdapter(aa1);

}
public void CheckBox(View view)
{
CheckBox cb1,cb2;

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 39


cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);

if(cb1.isChecked())
{
Toast.makeText(getApplicationContext(), "MCA is
Selectd",Toast.LENGTH_LONG).show();
}
else if(cb2.isChecked())
{
Toast.makeText(getApplicationContext(), "BTech is
Selectd",Toast.LENGTH_LONG).show();
}
}

public void RadioBox(View view)


{
RadioButton rb1,rb2;

rb1=(RadioButton)findViewById(R.id.rb1);
rb2=(RadioButton)findViewById(R.id.rb2);

if(rb1.isChecked())
{
Toast.makeText(getApplicationContext(), "male is
Selectd",Toast.LENGTH_LONG).show();
}
else if(rb2.isChecked())
{
Toast.makeText(getApplicationContext(), "Female is
Selectd",Toast.LENGTH_LONG).show();
}

public Dialog onCreateDialog(int index)


{
if(index==DATE_PICKER_DIALOG)
{
OnDateSetListener dl=new OnDateSetListener() {

public void onDateSet(DatePicker view, int year, int monthOfYear,


int dayOfMonth) {

Button b1=(Button)findViewById(R.id.dp);
b1.setText(dayOfMonth+"-"+(monthOfYear+1)+"-
"+year);

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 40


}
};
DatePickerDialog dpd=new DatePickerDialog(this,dl,2012,04,24);
return dpd;
}

else if(index==TIME_PICKER_DIALOG)
{
OnTimeSetListener tl=new OnTimeSetListener() {

public void onTimeSet(TimePicker view, int hourOfDay, int


minute) {

Button b1=(Button)findViewById(R.id.tp);
b1.setText(hourOfDay+"-"+minute);
}
};

TimePickerDialog tpd=new TimePickerDialog(this,tl,10,12,false);


return tpd;
}
return null;
}

public void StartDialog(View view)


{
showDialog(DATE_PICKER_DIALOG);
}
public void TimeDialog(View view)
{
showDialog(TIME_PICKER_DIALOG);
}

The Main.xml:

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


<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent" >
<TableRow >

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 41


<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Registration Form"
android:textStyle="bold|italic" > </TextView>
</TableRow>

<TableRow >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Name" > </TextView>

<EditText android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/et1" >
</EditText>
</TableRow>

<TableRow >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the University " >
</TextView>
<AutoCompleteTextView android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/act1" >
</AutoCompleteTextView>
</TableRow>

<TableRow >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select The Course " >
</TextView>

<Spinner android:layout_width="150px"
android:layout_height="50px"
android:id="@+id/sp1" > </Spinner>
</TableRow>

<TableRow >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select The Qualification " > </TextView>
<CheckBox
android:layout_width="50px" android:layout_height="wrap_content"
android:id="@+id/cb1"
android:text="MCA"
android:onClick="CheckBox" ></CheckBox>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 42


android:text="" ></TextView>
<CheckBox
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="@+id/cb2"
android:text="BTech"
android:onClick="CheckBox" ></CheckBox>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select The Gender" ></TextView>
<RadioGroup >
<RadioButton android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb1"
android:text="Male"
android:onClick="RadioBox" ></RadioButton>
<RadioButton
android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb2"
android:text="Female"
android:onClick="RadioBox" ></RadioButton>
</RadioGroup>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Course Joining Date" ></TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/dp"
android:text="Select Date"
android:onClick="StartDialog" ></Button>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prefered Timings" ></TextView>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tp"
android:text="Select Time"
android:onClick="TimeDialog" ></Button>
</TableRow>
</TableLayout>
</ScrollView>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 43


Dialog Box:

 The android.app.DialogInterface is the base interface representing


any dialog.
 The android.app.Dialog class supports declaring a dialog . This is the
base class for any dialog.

Example:

Dialog d=new Dialog(this);


d.setContentView(R.layout.dialog_layout);

The dialog_layout describes the view for the dialog just as done for the
activity.

d.setOwnerActivity(MyActivity,this);
d.show(); // This will show the dialog

we can add onCancelListener and onDismissListener’s set to the Dialog.

We use any of the following methods of Dialog to choose the dialog box.

Cancel();
Dismiss();

Android includes the following builtin dialogs implementation simplifying


creating the dialog box for most common requirements.

Alert Dialog

ProgressBar Dialog

DatePicker Dialog

TimePicker Dialog

The AlertDialog: This supports us to create a dialog that meets the most
common requirement of having a dialog for showing some alert, this includes

- A Optional Title
- Message Text
- Zero, one, two, or three buttons
- List of items

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 44


We use a ‘AlertDialog.Builder’ object to crate this Dialog .

The following methods of this object allows us setting the details for the
dialog.

- setTitle(String)
- setMessage(String)
- setPositiveButton(String lable,DialogInterface.OnClickLIstener
listener)
- setNegiveeButton(String lable,DialogInterface.OnClickLIstener
listener)
- setNutralButton(String lable,DialogInterface.OnClickLIstener
listener)
- setItems(String[])

Once setting all the details , we can invoke create() method for the
AlertDialog object and further show() method for showing.

The following methods of Activity can be used to show and remove


the Dialog boxes.

 showDialog(int): This shows the Dialog.


 removeDialog(int): Removes the dialog from the Activity
 The OnCreateDialog(int): method is invoked for the first time
when a dialog is requested to show. This method is responsible to
create a dialog for the given index to show.
 The onPrepareDialog(int): method is invoked each
time(including firsttime) when a dialog is required to show.

Note:
The Activity retains the state of the dialog even on cancelled /
dismiss of the dialog is requested to show again . However invoking
remove Dialog(int) will release the dialog state with the activity.

The Menu:
The following methods ‘Activity ‘ are invoked to create the
menu for the activity.

OnCreateOptionsMenu(menu):
This method is invoked for the first time the user clicks on the menu
for the activity.

Note: From Android 3.0 this is invoked at the time starting the Activity as the menu
here is always visible.

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 45


OnPrepareOptionsMenu(menu):

This is called each time when the menu is required to be show.

To Listen for the menu item click we can override the following method.

boolean onMenuItemSelected(int featureId,MenuItem m)

Sample Program on Dialog Boxes and Menu’’s:

package com.durgasoft.android;

import ......................................................................;

public class DialogsExampleActivity extends Activity {


private EditText time_et;
private Button date_button;
// Example for Dialog Boxes and the Menu
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
time_et=(EditText)findViewById(R.id.time_et);
date_button=(Button)findViewById(R.id.b2);
}
private static int BASIC_DIALOG=1;
private static int DATE_PICKER_DIALOG=2;
private static int TIME_PICKER_DIALOG=3;
private static int ALERT_DIALOG1=4;
private static int ALERT_DIALOG2=5;

public void button1Click(View v){


// Remove the comments One by One and check the result
//showDialog(BASIC_DIALOG);
//showDialog(ALERT_DIALOG2);
showDialog(ALERT_DIALOG1);
; }

public void button2Click(View v){


showDialog(DATE_PICKER_DIALOG);
}
public void button3Click(View v){

showDialog(TIME_PICKER_DIALOG);
}
public Dialog onCreateDialog(int index){

if(index==BASIC_DIALOG){
final Dialog d=new Dialog(this);
d.setContentView(R.layout.dialog1_layout);
Button b=(Button)d.findViewById(R.id.b2);
By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 46
b.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();
}
});
return d;
}else if (index==DATE_PICKER_DIALOG){

OnDateSetListener dl= new OnDateSetListener() {

public void onDateSet( DatePicker view, int year, int monthOfYear,


int dayOfMonth) {
Toast.makeText(getApplicationContext(), "Date : "+dayOfMonth+"-
"+(monthOfYear+1)+"-"+year, Toast.LENGTH_SHORT).show();
date_button.setText("New : "+ dayOfMonth+"-"+(monthOfYear+1)+"-"+year);
}
};

DatePickerDialog dpd=new DatePickerDialog(this, dl, 2011, 10, 12);


return dpd;
}else if (index==TIME_PICKER_DIALOG){

OnTimeSetListener dl=new OnTimeSetListener() {


public void onTimeSet(TimePicker tp, int arg1,int arg2) {
Toast.makeText(getApplicationContext(), "Time : "+arg1+":"+arg2,
Toast.LENGTH_SHORT).show();
String text="";
if (arg1 <= 12){
text=arg1+":"+arg2+" AM";
}else{
text=(arg1-12)+":"+arg2+" PM";
}
time_et.setText(text);
}
};

TimePickerDialog tpd=
new TimePickerDialog(
this,dl, 10, 12, false);
return tpd;
}else if (index == ALERT_DIALOG1){

AlertDialog.OnClickListener listener=
new AlertDialog.OnClickListener(){

public void onClick(


DialogInterface dialog,
int which) {
String text="";
if (which==AlertDialog.BUTTON_POSITIVE){
text="Positive : OK";

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 47


}else
if(which==AlertDialog.BUTTON_NEGATIVE){
text="Natative : Not OK";
}else {
text="Nutral : OK";
}
Toast.makeText(getApplicationContext(),
text, Toast.LENGTH_SHORT).show();
}
};

AlertDialog.Builder ab=
new AlertDialog.Builder(this);
ab.setTitle("Alert Dialog Sample");
ab.setMessage("You opened AlertDialog");
ab.setPositiveButton("OK", listener);
//ab.setNegativeButton("Not OK", listener);
//ab.setNeutralButton("Neutral", listener);

return ab.create();
}else if (index == ALERT_DIALOG2){

AlertDialog.Builder ab=
new AlertDialog.Builder(this);
ab.setTitle("Alert Dialog Sample");

final String[] items={"Abc1", "Abc2",


"Abc3", "Abc4"};

DialogInterface.OnClickListener listener=
new DialogInterface.OnClickListener() {

public void onClick(


DialogInterface dialog,
int which) {
Toast.makeText(
getApplicationContext(),
items[which],

Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
};

ab.setItems(items, listener);
return ab.create();
}else{
return null;
}
}

public void onPrepareDialog(int index, Dialog d){

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 48


if (index==BASIC_DIALOG){
EditText ev=(EditText)d.findViewById(R.id.et1);
TextView tv=(TextView)d.findViewById(R.id.tv1);
tv.setText(tv.getText()+":"+ ev.getText());
}
}

@Override
public boolean onCreateOptionsMenu(
Menu menu) {
MenuInflater mi=new MenuInflater(this);
mi.inflate(R.menu.menu1, menu);
return true;
}

@Override
public boolean onMenuItemSelected(
int featureId, MenuItem item) {

Toast.makeText(getApplicationContext(),
item.getTitle(), Toast.LENGTH_SHORT).show();

return true;
}

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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
></TextView>

<Button android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button1Click"
android:text="Show Dialog">
</Button>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="150px"

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 49


android:layout_height="wrap_content"
android:text="Alarm Date : ">
</TextView>

<Button android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button2Click"
android:text="Set Date">
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText android:id="@+id/time_et"
android:layout_width="100px"
android:layout_height="wrap_content">
</EditText>
<Button android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button3Click"
android:text="Show Time Dialog">
</Button>
</LinearLayout>
</LinearLayout>
dialog1_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a dialog box" ></TextView>
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="2"
android:id="@+id/et1" ></EditText>
<Button android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"></Button>
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></DatePicker></LinearLayout>

By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 50


my_tabs_view.xml:

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


<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/android:tabhost"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@id/android:tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

<FrameLayout
android:id="@id/android:tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

</LinearLayout>

</TabHost>

Menu1.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/m1"
android:title="Option1"></item>
<item android:id="@+id/m2"
android:title="Option2"></item>
<item android:id="@+id/m3"
android:title="Option3"></item>
<item android:id="@+id/m4"
android:title="Option4"></item>
<item android:id="@+id/m5"
android:title="File">
<menu >
<item android:id="@+id/m6"
android:title="Open"></item>
<item android:id="@+id/m7"
android:title="New"></item>
</menu>
</item>
</menu>
By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 51
By Mr. Mahesh Durga Soft Solutions , SR Nagar , Hyderabad . www.durgasoft.com 52

S-ar putea să vă placă și