You are on page 1of 54

Andorid 

Lab Manual 

LAB MANUAL

Android Lab
CSE-VII sem

CSE 7th Ssm  
Andorid Lab Manual 

Experiment 1:

How to setup Android for Eclipse IDE

CSE 7th Ssm  
Andorid Lab Manual 

Experiment 1:

1. How to setup Android for Eclipse IDE

Let's see the list of software required to setup android for eclipse IDE manually.

1. Install the JDK


2. Download and install the Eclipse for developing android application
3. Download and Install the android SDK
4. Intall the ADT plugin for eclipse
5. Configure the ADT plugin
6. Create the AVD
7. Create the hello android application

1) Install the Java Development Kit (JDK)

For creating android application, JDK must be installed if you are developing the android
application with Java language. download the JDK

2) Download and install the Eclipse IDE

For developing the android application using eclipse IDE, you need to install the Eclipse. you
can download it from this location download the Eclipse. Eclipse classic version is
recommended but we are using the Eclipse IDE for JavaEE Developers.

3) Download and install the android SDK

First of all, download the android SDK. In this example we have installed the android SDK for
windows (.exe version). Now double click on the exe file, it will be installed. I am using the
android 2.2 version here.

4) Download the ADT plugin for eclipse

ADT (Android Development Tools) is required for developing the android application in the
eclipse IDE. It is the plugin for Eclipse IDE that is designed to provide the integrated
environment.

CSE 7th Ssm  
Andorid Lab Manual 

For downloading the ADT, you need to follow these steps:

1) Start the eclipse IDE, then select Help > Install new software...

2) In the work with combo box, write https://dl-ssl.google.com/android/eclipse/

3) select the checkbox next to Developer Tools and click next

4) You will see, a list of tools to be downloaded here, click next

5) click finish

6) After completing the installation, restart the eclipse IDE

5) Configuring the ADT plugin

After the installing ADT plugin, now tell the eclipse IDE for your android SDK location. To do so:

1. Select the Window menu > preferences

CSE 7th Ssm  
Andorid Lab Manual 

2. Now select the android from the left panel. Here you may see a dialog box asking if you
want to send the statistics to the google. Click proceed.
3. Click on the browse button and locate your SDK directory e.g. my SDK location is
C:\Program Files\Android\android-sdk .
4. Click the apply button then OK.

6) Create an Android Virtual Device (AVD)

For running the android application in the Android Emulator, you need to create and AVD. For
creating the AVD:

1. Select the Window menu > AVD Manager


2. Click on the new button, to create the AVD
3. Now a dialog appears, write the AVD name e.g. myavd. Now choose the target android
version e.g. android2.2.
4. click the create AVD

7) create and run the simple android example

Visit the next page to create first android application.

CSE 7th Ssm  
Andorid Lab Manual 

Experiment 2:

Using the Development environment


a) Create a new Project using wizard
b) Add source and resource files.
c) Import existing projects into workspace
d) Create testing Emulator
e) Compile and run the project
f) Debug the project

CSE 7th Ssm  
Andorid Lab Manual 

Create the New Android project

For creating the new android project:

1) Select File > New > Project...

2) Select the android project and click next

3) Fill the Details in this dialog box and click finish

CSE 7th Ssm  
Andorid Lab Manual 

Now an android project have been created. You can explore the android project and see the
simple program, it looks like this:

Write the message

For writing the message we are using the TextView class. Change the onCreate method as:

1. TextView textview=new TextView(this);


2. textview.setText("Hello Android!");
3. setContentView(textview);

Let's see the full code of MainActivity.java file.

package com.example.helloandroid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {

CSE 7th Ssm  
Andorid Lab Manual 

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview=new TextView(this);
textview.setText("Hello Android!");
setContentView(textview);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Run the android application

To run the android application: Right click on your project > Run As.. > Android Application

The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting
the emulator, the eclipse plugin installs the application and launches the activity. You will see
something like this:

CSE 7th Ssm  
Andorid Lab Manual 

Experiment 3:
XML Files
a. AndroidManifest.xml
i. Edit the manifest and change min sdk and target
sdk of application.
ii. Add main activity entries in manifest.
iii. Add second activity entries in manifest.
iv. Add Entries for Service, Broadcast receivers.
v. Add uses permissions for reading files, internet,
camera.

CSE 7th Ssm  
Andorid Lab Manual 

The AndroidManifest.xml file contains information of your package, including components of


the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

o It is responsible to protect the application to access any protected parts by providing


the permissions.
o It also declares the android api that the application is going to use.
o It lists the instrumentation classes. The instrumentation classes provides profiling and
other informations. These informations are removed just before the application is
published etc.

This is the required xml file for all the android application and located inside the root directory.

A simple AndroidManifest.xml file looks like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javatpoint.hello"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

CSE 7th Ssm  
Andorid Lab Manual 

</application>

</manifest>

Elements of the AndroidManifest.xml file

The elements used in the above xml file are described below.

<manifest>

manifest is the root element of the AndroidManifest.xml file. It has package attribute that
describes the package name of the activity class.

<application>

application is the subelement of the manifest. It includes the namespace declaration. This
element contains several subelements that declares the application component such as activity
etc. The commonly used attributes are of this element are icon, label, theme etc.

android:icon represents the icon for all the android application components.

android:label works as the default label for all the application components.

android:theme represents a common theme for all the android activities.

<activity>

activity is the subelement of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required attribute.

<intent-filter>

intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.

CSE 7th Ssm  
Andorid Lab Manual 

<action>

It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>

It adds a category name to an intent-filter.

CSE 7th Ssm  
Andorid Lab Manual 

Layouts
i. Create Linear Layout in xml
ii. Create Relative Layout in xml
iii. Create frame layout in xml
iv. Create a complex mixed layout using all above
layouts

CSE 7th Ssm  
Andorid Lab Manual 

Android allows you to create view layouts using simple XML file (we can also create a layout
using java code). All the layouts must be placed in /re s / l a y o u t folder.

Okay, now let's get started with the view layouts.

1. Linear Layout

In a linear layout, like the name suggests, all the elements are displayed in a linear
fashion(below is an example of the linear layouts), either H o r iz o n t a l l y or V e r t i c a l l y and
this behavior is set in a n d r o id : o r ie n t a t i o n which is an attribute of the node LinearLayout.
Example of Vertical layout snippet

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

CSE 7th Ssm  
Andorid Lab Manual 

Example of Horizontal layout snippet

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

Now that we know the two types of linear layouts, here are the steps you need to follow to
create them

1. Create a new project File -> New -> Android Project


2. In Package Explorer right click on r e s / la y o u t folder and create a new Android XML File
and name it as you wish. I am naming it as “l in e a r_ la y o u t .x m l ”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “l in e a r_ l a yo u t .x m l”) and type the following
code.

<?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="match_parent"
android:layout_height="match_parent">

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"


android:text="Email:" android:padding="5dip"/>

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


android:layout_marginBottom="10dip"/>

<Button android:layout_width="fill_parent" android:layout_height="wrap_content"


android:text="Login"/>

CSE 7th Ssm  
Andorid Lab Manual 

<!-- 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="25dip">

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"


android:text="Home" android:padding="15dip" android:layout_weight="1"
android:gravity="center"/>

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"


android:text="About" android:padding="15dip" android:layout_weight="1"
android:gravity="center"/>

</LinearLayout>

</LinearLayout>

4. To set this newly created view as the initial view of your app, Open your MainActivity.java file.
You would see the following line inside
the o n C r e a t e function s e tC o n t e n t V iew ( R .la y o u t . m a in ) .
Change R . l a yo u t . m a in toR . la y o u t . y o u r l i n e a r v i ew n a m e . In my case
its R . l a y o u t . l i n e a r _ la y o u t

package com.example.androidlayouts;
import android.app.Activity;
import android.os.Bundle;

public class AndroidLayoutsActivity extends Activity {

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

5. To run the application, right click on the project -> Run As -> 1. Android Application. You
should see your newly created linear layout in the emulator.

CSE 7th Ssm  
Andorid Lab Manual 

2. Relative Layout

In a relative layout every element arranges itself relative to other elements or a parent element.
As an example, lets consider the layout defined below. The “C a n c e l” button is placed
relatively, to the r ig h t o f the “L o g in ” button p a ra l le l y . Here is the code snippet that
achieves the mentioned alignment (Right of Login button parallely)
Example code snippet

<Button android:id="@+id/btnLogin" ..></Button>

<Button android:layout_toRightOf="@id/btnLogin"
android:layout_alignTop="@id/btnLogin" ..></Button>

CSE 7th Ssm  
Andorid Lab Manual 

Here are the steps to create a relative layout

1. Create a new project File -> New -> Android Project


2. In Package Explorer right click on r e s / la y o u t folder and create a new Android XML File
and name it as you wish. I am naming it as “relative_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “r e la t iv e _ la y o u t .x m l ”) and type the
following code.

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

<TextView android:id="@+id/label" android:layout_width="fill_parent"


android:layout_height="wrap_content" android:text="Email" />

<EditText android:id="@+id/inputEmail" android:layout_width="fill_parent"


android:layout_height="wrap_content" android:layout_below="@id/label" />

<Button android:id="@+id/btnLogin" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:layout_below="@id/inputEmail"
android:layout_alignParentLeft="true" android:layout_marginRight="10px"
android:text="Login" />

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:layout_toRightOf="@id/btnLogin"
android:layout_alignTop="@id/btnLogin" android:text="Cancel" />

CSE 7th Ssm  
Andorid Lab Manual 

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:layout_alignParentBottom="true" android:text="Register new Account"
android:layout_centerHorizontal="true"/>
</RelativeLayout>

4. Same like before open your MainActivity.java file and set the layout to your newly created
relative layout file. In my case its R . l a yo u t .r e l a t i v e _ la y o u t
setContentView(R.layout.relative_layout);
5. To run the application, right click on the project -> Run As -> 1. Android Application. You
should see your newly created relative layout in the emulator.

3. Table Layout

Table layouts in Android works in the same way HTML table layouts work. You can divide your
layouts into r ow sand c o lu m n s . Its very easy to understand. The image below should give
you an idea.

CSE 7th Ssm  
Andorid Lab Manual 

1. Create a new project File -> New -> Android Project


2. In Package Explorer right click on res/layout folder and create a new Android XML File and
name it as you wish. I am naming it as “table_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “t a b l e _ l a y o u t . x m l ”) and type the following
code.

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*" android:stretchColumns="*" android:background="#ffffff">
<!-- Row 1 with single column -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="18dp" android:text="Row 1" android:layout_span="3"
android:padding="18dip" android:background="#b0b0b0"
android:textColor="#000"/>
</TableRow>

CSE 7th Ssm  
Andorid Lab Manual 
<!-- Row 2 with 3 columns -->
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 1"
android:layout_weight="1" android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 2"
android:layout_weight="1" android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 3"
android:layout_weight="1" android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>

<!-- Row 3 with 2 columns -->


<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 1"
android:layout_weight="1" android:background="#b0b0b0"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>

<TextView
android:id="@+id/TextView04" android:text="Row 3 column 2"
android:layout_weight="1" android:background="#a09f9f"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>

</TableLayout>
4. Same like before open your MainActivity.java file and set the layout to your newly created
table layout file. In my case its R . l a y o u t .t a b l e _ la y o u t

setContentView(R.layout.table_layout);

CSE 7th Ssm  
Andorid Lab Manual 

5. To run the application, right click on the project -> Run As -> 1. Android Application. You
should see your newly created table layout in the emulator.

CSE 7th Ssm  
Andorid Lab Manual 

c. Drawables
i. Create xml drawable for rectangular, oval and other
basic shapes
ii. Create xml drawable with Layer list for complex
shapes.

CSE 7th Ssm  
Andorid Lab Manual 

There are at least 17 types of drawables but there are five that are most important to
understand:

1. Shape Drawables - Defines a shape with properties such as stroke, fill, and padding
2. StateList Drawables - Defines a list of drawables to use for different states
3. LayerList Drawables - Defines a list of drawables group together into a composite
result
4. NinePatch Drawables - A PNG file with stretchable regions to allow proper resizing
5. Vector Drawables - Defines complex XML-based vector images

Let's explore these drawable file types one by one and take a look at examples of usage.

Drawing Shapes

The Shape Drawable is an XML file that defines a geometric shape, including colors and
gradients. This is used to create a complex shape that can then be attached as the background
of a layout or a view on screen. For example, you can use a shape drawable to change the
shape, border, and gradient of a button background.

A shape is simply a collection of properties that are combined to describe a background. The
shape can be described with properties such as corners for rounding, gradient for
backgrounds, padding for spacing, solid for background colors, andstroke for border.

Solid Color Shapes

Here's an example of drawing a rounded rectangle with a border


in res/layout/drawable/solid_color_shape.xml:

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="4dp" />
<stroke android:width="4dp" android:color="#C1E1A6" />
<solid android:color="#118C4E"/>
<padding android:left="20dp" android:top="20dp"
android:right="20dp" android:bottom="20dp" />
</shape>

and then applied to a TextView using the background property:

CSE 7th Ssm  
Andorid Lab Manual 

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/solid_color_shape"
android:textColor="#ffffff"
android:text="@string/hello_world" />

and the resulting view looks like:

Note that drawables can be applied to any view and are usually set with
the background property referencing the drawable resource.

Gradient Colored Shapes

Shapes also support gradients backgrounds as well supporting properties such


as startColor, centerColor, endColor,angle. Different gradients such as radial, linear or sweep
can be selected using the type property.
Here's an example of a simple linear gradient shape specified
in res/layout/drawable/gradient_shape.xml:

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="4dp" />
<stroke android:width="1dp" android:color="#0078a5" />
<gradient
android:startColor="#0078a5" android:endColor="#00adee"
android:angle="90"/>
<padding android:left="8dp" android:top="2dp"
android:right="8dp" android:bottom="2dp" />
</shape>

applied to a button and the resulting view looks like:

CSE 7th Ssm  
Andorid Lab Manual 

You can also setup radial-type gradients with:

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="4dp" />
<stroke android:width="4dp" android:color="#CCFFFF" />
<gradient
android:startColor="#0078a5"
android:endColor="#CCFFFF"
android:gradientRadius="250"
android:type="radial"
/>
<padding android:left="30dp" android:top="30dp"
android:right="30dp" android:bottom="30dp" />
</shape>

and applied to a TextView, this looks like:

Using solid color shapes and gradients we can customize the appearance of buttons, layouts
and other views without requiring the use of any images. Note that custom shapes can be
created at runtime using other shape drawable types using PathShape andArcShape.

State List

A StateListDrawable is a drawable object defined in XML that uses a several different images to
represent the same graphic, depending on the state of the object. For example, a Button widget
can exist in one of several different states (pressed, focused, or neither) and, using a state list
drawable, you can provide a different background image for each state. The state list supports
different view states such

CSE 7th Ssm  
Andorid Lab Manual 

as android:state_pressed, android:state_focused, android:state_enabled,android:state_selected


, among many others. The illustration below shows all the major states that can be represented:
For example, a state list XML for a button background might look like the following in a file such
asres/drawable/selector_button_bg:

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


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/button_pressed" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/button_focused" />
<item
android:state_enabled="true"
android:drawable="@drawable/button_enabled" />
</selector>

Now, when the view (i.e button) is pressed or focused, the drawable used for the view will
change accordingly. Note that any view can have a state selector, but the most common uses
are with buttons and listview items. There are also color state selectors which allow a color to be
chosen based on view state such as in a file named res/color/button_text.xml:

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


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#ffff0000"/>
<item android:state_focused="true" android:color="#ff0000ff"/>
<item android:color="#ff000000"/>
</selector>

and applied to any field that accepts a color value such as the textColor property of a button in a
layout file:

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />

Using state lists allows us to easily define dynamic views that respond to pressed, checked,
enabled or other related states.

CSE 7th Ssm  
Andorid Lab Manual 
Creating Vector Drawables

To create a vector image, you need to define pathData syntax which is located here. This
example defines the details of the shape inside a XML element such
as res/drawable/ic_heart.xml with:

<!-- res/drawable/ic_heart.xml -->


<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="256dp"
android:width="256dp"
android:viewportWidth="32"
android:viewportHeight="32">
<!-- draw a path -->
<path android:fillColor="#c9c10606"
android:pathData="M20.5,9.5
c-1.955,0,-3.83,1.268,-4.5,3
c-0.67,-1.732,-2.547,-3,-4.5,-3
C8.957,9.5,7,11.432,7,14
c0,3.53,3.793,6.257,9,11.5
c5.207,-5.242,9,-7.97,9,-11.5
C25,11.432,23.043,9.5,20.5,9.5z" />
</vector>

Using Vector Drawables

We can then load vectors using the app:srcCompat property:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_heart" />
</RelativeLayout>

Customizing a Button

Let's take a look at an end-to-end example of customizing a button using drawables to govern
the styling and the pressed states.

Creating a custom button require combining at least a state list drawable with a shape drawable.
First, let's create our shape drawable which represents the "default" button background
in res/drawable/nice_button_enabled.xml:

CSE 7th Ssm  
Andorid Lab Manual 

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#0078a5"
android:endColor="#00adee"
android:angle="90"/>
<padding android:left="15dp"
android:top="1dp"
android:right="15dp"
android:bottom="1dp" />
<stroke
android:width="1dp"
android:color="#0076a3" />
<corners android:radius="8dp" />
</shape>

Let's also create a style (set of view properties) that includes setting the background
in res/values/styles.xml:

<style name="NiceButton" parent="@android:style/Widget.Button">


<item name="android:gravity">center_vertical|center_horizontal</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:background">@drawable/nice_button_enabled</item>
<item name="android:textSize">16sp</item>
<item name="android:textStyle">bold</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
</style>

This now represents the shape and background of the button in the default state along with all
the other properties. We could apply this by setting the style of the button:

<Button
android:id="@+id/btnGo"
style="@style/NiceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

If we run that, we will see the following button:

CSE 7th Ssm  
Andorid Lab Manual 
Customizing a ListView

Another common task is customizing the appearance of items in a ListView. First let's create the
basic ListView and populate String items inside. First, the layout XML for the item
in res/layout/item_simple.xml:

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


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:padding="5dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />

Next, let's setup the basic ListView xml in an activity:

<ListView
android:id="@+id/lvTest"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>

and then populate the ListView with items:

ArrayList<String> items = new ArrayList<String>();


for (int i = 1; i < 8; i++) {
items.add("Item " + i);
}
ArrayAdapter<String> aItems = new ArrayAdapter<String>(this, R.layout.item_simple, items);
lvTest = (ListView) findViewById(R.id.lvTest);
lvTest.setAdapter(aItems);

This results in the following default styles ListView:

CSE 7th Ssm  
Andorid Lab Manual 

Now, let's add our own styling to the ListView. Let's add a default gradient and a pressed
gradient, change the divider color between items and add a border around the ListView. First,
let's add the shape gradient background for the default state inres/drawable/gradient_bg.xml:

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#f1f1f2"
android:centerColor="#e7e7e8"
android:endColor="#cfcfcf"
android:angle="270" />
</shape>

and then for the pressed gradient background in res/drawable/gradient_pressed_bg.xml:

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"

CSE 7th Ssm  
Andorid Lab Manual 

android:shape="rectangle">
<gradient
android:startColor="#C1E1A6"
android:endColor="#118C4E"
android:angle="270" />
</shape>

and then let's create a state list which describes the drawables to use in various list states
inres/drawable/states_selector_list.xml:

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


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg" />

<item android:state_pressed="true"
android:drawable="@drawable/gradient_pressed_bg" />

<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/gradient_pressed_bg" />
</selector>

Next, let's setup the border for our ListView using a Shape drawable
in res/drawable/list_border.xml by setting the "stroke" property:

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke android:width="1dp" android:color="#b5b5b5" />
<solid android:color="#00000000" />
</shape>

Let's now apply each of these XML drawables to the various elements. First, let's add the
background to the list item itself and tweak res/layout/item_simple.xml:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
...
android:background="@drawable/states_selector_list" />

Notice that the background property has been set to the states list in order to apply the default
background for the item. Next, let's add the border and the selector states to the existing
ListView in the activity layout file:

CSE 7th Ssm  
Andorid Lab Manual 

<ListView
...
android:padding="1dp"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:background="@drawable/list_border"
android:listSelector="@drawable/states_selector_list" >
</ListView>

Here we have customized the divider color and dividerHeight as well as the background to apply
the border andlistSelector to manage the states when an item is pressed. With all this in place,
our customized ListView now looks like:

We've now successfully customized the appearance of our ListView and it's items using a series
of drawables. You can use these techniques to make a list look however you want based on the
needs for your app.

CSE 7th Ssm  
Andorid Lab Manual 

d. Values

i. Create strings.xml to store all your application strings.


ii. Create color.xml to store all your color values
iii. Create styles.xml to store all your custom themes and
style objects

A single string that can be referenced from the application or from other resource files (such as
an XML layout).

FILE LOCATION:

CSE 7th Ssm  
Andorid Lab Manual 

res/values/filename.xml
The filename is arbitrary. The <string> element's name will be used as the resource ID.

COMPILED RESOURCE DATATYPE:

Resource pointer to a String.

RESOURCE REFERENCE:

In Java: R.string.string_name
In XML:@string/string_name

SYNTAX:

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


<resources>
<string
name="string_name"
>text_string</string>
</resources>

ELEMENTS:

<resources>

Required. This must be the root node.

No attributes.

<string>

A string, which can include styling tags. Beware that you must escape apostrophes and
quotation marks. For more information about how to properly style and format your
strings see Formatting and Styling, below.

attributes:

name

String. A name for the string. This name will be used as the resource ID.

CSE 7th Ssm  
Andorid Lab Manual 

EXAMPLE:

XML file saved at res/values/strings.xml:

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


<resources>
<string name="hello">Hello!</string>
</resources>

This layout XML applies a string to a View:

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

This application code retrieves a string:

String string = getString(R.string.hello);

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain
any rich text styling applied to the string

CSE 7th Ssm  
Andorid Lab Manual 

Experimeny No. 4
Creating User Interface
a.Create application with Basic Views (Textview,
Button, ListView)
b. Create application with different Layouts (Linear,
Relative, Frame)
c.Create application to handle and respond on click
using Click Listeners

For doing this, first make a string array in a string file, this file is automatically generated in
the value folder in the res folder as in the following:

CSE 7th Ssm  
Andorid Lab Manual 

Put the following code in this file:

<string-array name="listdata">

<item>item 1</item>

<item>item 2</item>

<item>item 3</item>

<item>item 4</item>

<item>item 5</item>

<item>item 6</item>

<item>item 7</item>

<item>item 8</item>

<item>item 9</item>

<item>item 10</item>

<item>item 11</item>

<item>item 12</item>

<item>item 13</item>

<item>item 14</item>

<item>item 15</item>

<item>item 16</item>

<item>item 17</item>

<item>item 17</item>

CSE 7th Ssm  
Andorid Lab Manual 
<item>item 18</item>

<item>item 19</item>

<item>item 20</item>

</string-array>

Then make a layout for the activity with the code below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/container"

android:layout_width="match_parent"

android:layout_height="match_parent" >

<ListView

android:id="@+id/listView"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

</ListView>

</RelativeLayout>

Then make the child layout for the list, the code is below:

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

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

CSE 7th Ssm  
Andorid Lab Manual 
tools:context="com.example.articalonlistiner.MainActivity$PlaceholderFragment" >

<TextView

android:id="@+id/childTextView"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_alignParentLeft="true" />

<Button

android:id="@+id/childButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentRight="true"

android:text="Click Me" />

</RelativeLayout>

Now make the reference of the ListView and Adapter.

Make an activity (MainActivity.java) in the src folder.

CSE 7th Ssm  
Andorid Lab Manual 

Write that code in the MainActivity.

private ListView listView;

ListAdapter adapter;

ArrayList<String> dataItems = new ArrayList<String>();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

String[] dataArray = getResources().getStringArray(R.array.listdata);

List<String> dataTemp = Arrays.asList(dataArray);

dataItems.addAll(dataTemp);

listView = (ListView) findViewById(R.id.listView);

adapter = new ListAdapter(MainActivity.this, dataItems);

adapter.setCustomButtonListner(MainActivity.this);

listView.setAdapter(adapter);

CSE 7th Ssm  
Andorid Lab Manual 
}

This code shows the error because you have not made the ListAdapter.java file in the src
folder. Please make that file and extend it with ArrayAdapter<String>.

public class ListAdapter extends ArrayAdapter<String>

Then make the constructor of the ListAdapter as in the following:

public ListAdapter(Context context, ArrayList<String> dataItem) {

super(context, R.layout.child_listview, dataItem);

this.data = dataItem;

this.context = context;

There R.layout.child_listview is the child view of the ListView.

Now make an interface in ListAdapter, this interface works like a listener for the button.

customButtonListener customListner;

public interface customButtonListener {

public void onButtonClickListner(int position,String value);

And make a method to set the instance of the activity that has a ListView.

public void setCustomButtonListner(customButtonListener listener) {

this.customListner = listener;

This method shares the context of the MainActivity with the interface to use this.

Make a child class in ListAdapter.

public class ViewHolder {

TextView text;

Button button;

CSE 7th Ssm  
Andorid Lab Manual 
}

If you have more items in the listItem view then add all the reference in the ViewHolder class.

Now focus on the getview method of the adapter.

For this override the getView method.

@Override

public View getView(final int position, View convertView, ViewGroup parent) {

ViewHolder viewHolder;

if (convertView == null) {

LayoutInflater inflater = LayoutInflater.from(context);

convertView = inflater.inflate(R.layout.child_listview, null);

viewHolder = new ViewHolder();

viewHolder.text = (TextView) convertView

.findViewById(R.id.childTextView);

viewHolder.button = (Button) convertView

.findViewById(R.id.childButton);

convertView.setTag(viewHolder);

} else {

viewHolder = (ViewHolder) convertView.getTag();

final String temp = getItem(position);

viewHolder.text.setText(temp);

viewHolder.button.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

if (customListner != null) {

customListner.onButtonClickListner(position,temp);

CSE 7th Ssm  
Andorid Lab Manual 
}

});

return convertView;

Note: Here the yellow marked function is new for you. This is the main function to provide a
listener for the button of each item of the list view. This function returns a callback
forMainActivity because the MainActivity shares our context with the listener.

To use this you should implement this interface in MainActivity.

public class MainActivity extends Activity implements

customButtonListener

After implementing, this interface overrides the method. The method gives you the position of
the list adapter.

I implemented it only to show the toast. In it is the code of my function.

@Override

public void onButtonClickListner(int position, String value) {

Toast.makeText(MainActivity.this, "Button click " + value,

Toast.LENGTH_SHORT).show();

The output of this article is like:

CSE 7th Ssm  
Andorid Lab Manual 

You can implement your method, whatever you want to do with the button.

Here is the simple Toast.

This article is over now. The following is the entire code of the MainActivity and List Adapter.

MainActivity

package com.example.articalonlistiner;

CSE 7th Ssm  
Andorid Lab Manual 
import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import com.example.articalonlistiner.ListAdapter.customButtonListener;

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

import android.widget.ListView;

import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements

customButtonListener {

private ListView listView;

ListAdapter adapter;

ArrayList<String> dataItems = new ArrayList<String>();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

String[] dataArray = getResources().getStringArray(R.array.listdata);

List<String> dataTemp = Arrays.asList(dataArray);

dataItems.addAll(dataTemp);

listView = (ListView) findViewById(R.id.listView);

adapter = new ListAdapter(MainActivity.this, dataItems);

adapter.setCustomButtonListner(MainActivity.this);

listView.setAdapter(adapter);

CSE 7th Ssm  
Andorid Lab Manual 

@Override

public void onButtonClickListner(int position, String value) {

Toast.makeText(MainActivity.this, "Button click " + value,

Toast.LENGTH_SHORT).show();

ListAdapter

import java.util.ArrayList;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.TextView;

public class ListAdapter extends ArrayAdapter<String> {

customButtonListener customListner;

public interface customButtonListener {

public void onButtonClickListner(int position,String value);

CSE 7th Ssm  
Andorid Lab Manual 
public void setCustomButtonListner(customButtonListener listener) {

this.customListner = listener;

private Context context;

private ArrayList<String> data = new ArrayList<String>();

public ListAdapter(Context context, ArrayList<String> dataItem) {

super(context, R.layout.child_listview, dataItem);

this.data = dataItem;

this.context = context;

@Override

public View getView(final int position, View convertView, ViewGroup parent) {

ViewHolder viewHolder;

if (convertView == null) {

LayoutInflater inflater = LayoutInflater.from(context);

convertView = inflater.inflate(R.layout.child_listview, null);

viewHolder = new ViewHolder();

viewHolder.text = (TextView) convertView

.findViewById(R.id.childTextView);

viewHolder.button = (Button) convertView

.findViewById(R.id.childButton);

convertView.setTag(viewHolder);

} else {

viewHolder = (ViewHolder) convertView.getTag();

final String temp = getItem(position);

CSE 7th Ssm  
Andorid Lab Manual 
viewHolder.text.setText(temp);

viewHolder.button.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

if (customListner != null) {

customListner.onButtonClickListner(position,temp);

});

return convertView;

public class ViewHolder {

TextView text;

Button button;

CSE 7th Ssm  
Andorid Lab Manual 

Experiment No. 5
Assets and Images
a. Create application which will access files from Assets
folder (Images, sounds, Custom Fonts)

CSE 7th Ssm  
Andorid Lab Manual 
First, create a project as usual, then put files into ‘asset‘ like below:

Files in 'Assets'

Now, create a simple layout containing a TextView for displaying the content of ‘text.txt‘ and
an ImageView for displaying the image ‘avatar.jpg’, which are put in Asset.
The implementation quite easy using AssetManager as mentioned above.
package pete.android.study;

import java.io.IOException;
import java.io.InputStream;

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

public class Main extends Activity {

ImageView mImage;
TextView mText;

@Override
public void onCreate(Bundle savedInstanceState) {

CSE 7th Ssm  
Andorid Lab Manual 
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mImage = (ImageView)findViewById(R.id.image);
mText = (TextView)findViewById(R.id.text);
loadDataFromAsset();
}

public void loadDataFromAsset() {


// load text
try {
// get input stream for text
InputStream is = getAssets().open("text.txt");
// check size
int size = is.available();
// create buffer for IO
byte[] buffer = new byte[size];
// get data to buffer
is.read(buffer);
// close stream
is.close();
// set result to TextView
mText.setText(new String(buffer));
}
catch (IOException ex) {
return;
}

// load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");

CSE 7th Ssm  
Andorid Lab Manual 
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
return;
}

}
}

That’s a quick sample code giving this result.

Read data from Asset

CSE 7th Ssm  

You might also like