You are on page 1of 58

UNIT-II

UNIT III

Application Structure(in detail):AndroidManifest.xml,uses-


permission&uses-sdk, Resources & R.java , Assets , Layouts
& Drawable Resources ,Activities and Activity lifecycle ,
First sample Application
Emulator-Android Virtual Device: Launching emulator ,
Editing emulator settings, Emulator shortcuts , Logcat usage ,
Introduction to DDMS, Basic UI design, Preferences, Menu,
Intents, UI design, Tabs and Tab Activity, Styles & Themes ,
Examples.
AndroidManifest.xml
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:
It is responsible to protect the application to access any
protected parts by providing the permissions.
It also declares the android api that the application is
going to use.
It lists the instrumentation classes.
The instrumentation classes provides profiling and other
informations.
A simple AndroidManifest.xml file looks like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="com.FirstProject.hello"   android:versionCode="1"   android:version
Name="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>  
    </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, launch Mode 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.
<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.
Android R.java file
Android R.java is an auto-generated file by aapt (Android
Asset Packaging Tool) that contains resource IDs for all the
resources of res/ directory.
If you create any component in the activity_main.xml file, id
for the corresponding component is automatically created in
this file. This id can be used in the activity source file to
perform any action on the component.
Note: If you delete R.jar file, android creates it automatically.
Resources

 Android supports that resources, like images and certain XML configuration files,
can be keep separate from the source code, these resources must be stored in ‘res’
folder.
Resource Folder Description
Used to define strings, colors, dimensions, styles and sta
Simple Values /res/values
arrays of strings or integers. By convention each type is
stored in a separate file, e.g. strings are defined in the
res/values/strings.xml file.
Layouts
XML file with layout description files used to define the
/res/values
user interface for Activities and Fragments.
Styles and /res/values
Files which define the appearance of your Android
Themes
application.
Animations /res/animator
Define animations in XML for the property animation A
which allows to animate arbitrary properties of objects o
time.
Menus /res/menu
Define the properties of entries for a menu.
Assets
While the res directory contains structured values which are known to the
Android platform the assets directory can be used to store any kind of data.
You access this data via the AssetsManager which you can access
the getAssets() method.
AssetsManager allows to read an assets as InputStream with
the open() method.

// Get the AssetManager


AssetManager manager = getAssets();
// Read a Bitmap from Assets
try
{
InputStream open = manager.open("logo.png");
Bitmap bitmap = BitmapFactory.decodeStream(open);
// Assign the bitmap to an ImageView in this layout
ImageView view = (ImageView) findViewById(R.id.imageView1);
view.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
Activity and Activity Life cycle:
 Activity:
 An Activity is a visual representation of an android application. Activity uses
views and fragments to create user interface and to interact with users. An
Android application can have several activities.
 Views:
 Views are user interface widgets, e.g. buttons or text fields. Views have
attributes which can be used to configure their appearance and behavior.
 View Groups:
 A View Group is responsible for arranging other Views. View Groups is also
called layout managers.
 View Groups can be nestled to create complex layouts. You should not
nestle View Groups too deeply as this has a negative impact on the
performance.
11 of 13
An activity has essentially four states:
 running : If an activity in the foreground of the screen (at the
top of the stack).
 paused : If an activity has lost focus but is still visible.
 A paused activity is completely alive(it maintains all state
and member information and remains attached to the window
manager), but can be killed by the system in extreme low
memory situations.
 stopped : If an activity is completely hidden by another activity,
it is stopped.
Still retains all states and member functions.
Will be killed by System, when memory is needed elsewhere.
 finished : If an activity is paused or stopped, the system can
drop the activity from memory by either asking it to finish, or
simply killing its process.
 When it is displayed again to the user, it must be completely
restarted and restored to its previous state.
Android Activity Lifecycle methods
Android Emulator
 Android Emulator simulates Android devices
on your computer so that you can test your
application on a variety of devices
and Android API levels without needing to have
each physical device. 
 The emulator behaves like a real Android
device (in most cases) and allows you to test
your application without having a real device.
 You can configure the following to android
emulator:
 Android version,
 SD Card size,
 Screen Resolution,
 Other relevant settings.
Create and run Android Virtual Device
To define an Android Virtual Device (ADV) open the AVD
Manager dialog via Windows → AVD Manager and press New button
Create and run Android Virtual Device cont…

16
of 8
Create and run Android Virtual Device cont…

17
of 8
Create and run Android Virtual Device cont…
Create and run Android Virtual Device cont…
Emulator shortcuts

 The following shortcuts are useful for working with the emulator.

Alt+Enter maximizes the emulator.


Ctrl+F11 change the orientation of the emulator.
F8 Turns network on / off.

21
of 8
Dalvik Debug Monitor Server (DDMS)

• Eclipse provides a perspective for interacting with your Android (virtual)


device and your Android application program by DDMS.
• Select Window → Open Perspective → Other → DDMS to open this
perspective.

 Examples:

1. Used to make calls and send SMS to devices

2. Used to set current geo-position.

22
of 8
Log Cat
• Logcat is a tool which acts a console for android devices.
• You can see the log (including System.out.print() statements) via the LogCat
view.

23
of 8
View
The basic building block for user interface is
a View object which is created from the View class and
occupies a rectangular area on the screen and is
responsible for drawing and event handling. View is the
base class for widgets, which are used to create
interactive UI components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides
invisible container that hold other Views or other
ViewGroups and define their layout properties.
Android Layout Types
There are number of Layouts provided by Android
which you will use in almost all the Android applications
to provide different view, look and feel.
Basic UI Design
 Form Widgets:

1. Text View
2. Edit Text
3. Button
4. Check Box
5. Radio Button
6. Toggle Button
7. Spinner

26 8. Progress Bar
of
23
Basic UI Designs
 8. Image View
 9. AutoCompleteTextView

27
of
23
Text View
• Labels are components used to show text.
• A label displays text which is specified by the Text property. Other properties, all
of which can be set in the Graphical Layout, control the appearance and
placement of the text.

 Properties:
• BackgroundColor //Color for label background.
• FontSize //Point size for label text.
• Height //Label height (y-size).
• Width //Label width (x-size).
• Text //Text to display on label.
• TextAlignment //Left, center, or right.
• TextColor //Color for label text.
• 28
Visible //If set, label is visible.
of
23
Text View
 TextView tv;
 tv= (TextView)findViewById(int i);
 //initialization of text view object.
 // “i” is an unique integer in R.java file

 Methods:
• tv.setText(“Hello”) //sets the text inside method as label.
• tv.setTextColor(int i) //sets a particular color to text view.
• tv.getText() //returns the text from the text view.
• tv.setOnClickListener(OnclickListener l)
 //sets an onClickListener to the respective
component

29
of
23
Edit Text
• Edit text allows user to enter some text; generally it is used to take
input from the user in the form of text.

 Properties :
• FontSize //Point size for label text.
• Height //Label height (y-size).
• Width //Label width (x-size).
• Text //Text to display on label.
• TextColor //Color for label text.

30
of
23
Edit Text
 EditText et;
 et=(EditText)findViewById(int i); //initialization of text view object.
 // “i” is an unique integer in R.java file

 Methods:
• et.setText(“Hello”); //used to set a particular text to edittext
• et.getText(); //returns a string which has the content
inside edittext.
• et.setTextSize(20); // used to set a particular size to text.
• et.setTextColor(Color.RED) //used to set a color to the text.
• et.setEnabled(false); //used to enable/disable a component.

31
of
23
Button
• Buttons are components that users touch to perform some action in
your application. Buttons detect when users tap them. Many
aspects of a button's appearance can be changed. 

• Properties:
• BackgroundColor //Color for button background.
• Enabled //If set, user can tap button to cause action.
• FontSize //Point size for button text.
• Height //Button height (y-size).
• Width //Button width (x-size).
• Image //Image to display on button.
• Text //Text to display on button.
• TextAlignment //Left, center, or right.
• TextColor //Color for button text.
32
of
23
Button
 Button btn;
 btn=(Button)findViewById(int i); //initialization of button object.
 // “i” is an unique integer in R.java file

 Methods:
• btn.setEnabled(false) //used to enable or disable a button.
• btn.setOnClickListener(onClickListener l)
 // used to set an click listener
• btn.setText(“submit”) //used to set text for button component.
• btn.setTextColor(Color.BLACK)
 //used to set color to text of a button.

33
of
23
CheckBox
• CheckBoxes are components which allows to select multiple
options from available list of options.

• Properties:
• Height // check box height(y-size)
• Width // check box width(x-size)
• Text // Text for check box
• checked // indicates the intial checked state

34
of
23
CheckBox
 CheckBox cb;
 cb=(CheckBox)findViewById(int i); //initialization of check boxobject.
 // “i” is an unique integer in R.java file

 Methods:
• cb.isChecked() //returns a boolean value, true if check box is
selected, false if not selected.
• cb.setSelected(true) //used to check or uncheck a check box.
• cb.setOnCheckChangedListener(checkChangedListener l);
 // used to set check changed listner

35
of
23
RadioButton
• RadioButton is a components which allows to select a single
option from available list of options.

• Properties:
• Height // Radiobutton height(y-size)
• Width // Radiobutton width(x-size)
• Text // Text for Radiobutton
• checked // indicates the intial checked state

36
of
23
RadioButton
 RadioButton rb;

 rb=(RadioButton)findViewById(int i); //initialization of radio button


object.
 // “i” is an unique integer in R.java file
 Methods:

• rb.isChecked() //returns a boolean value, true if radio button is


selected, false if not selected.
• rb.setSelected(true) //used to select a radio button.
• rb.setOnCheckChangedListener(checkChangedListener l);
 // used to set check changed listner
37
of
23
Toggle Button
• Toggle Button is a components which works like a switch and has
two states.

• Properties:
• Height // Toggle height(y-size)
• Width // Toggle width(x-size)
• checked // indicates the initial checked state of toggle button

38
of
23
Toggle Button
ToggleButton tb;

tb=(ToggleButton)findViewById(int i); //initialization of toggle button


object.
 // “i” is an unique integer in R.java file
Methods:

• tb.isChecked() //returns a boolean value, true if toggle button is


selected, false if not selected.
• tb.setSelected(true) //used to select a radio button.
• tb.setOnCheckChangedListener(checkChangedListener l);

39 // used to set check changed listner


of
23
Spinner
• Spinners provide a quick way to select one value from a set. In the
default state, a spinner shows its currently selected value.
Touching the spinner displays a dropdown menu with all other
available values, from which the user can select a new one.

• Properties:
• Height // spinner height(y-size)
• Width // spinner width(x-size)
• Enabled // used to enable or disable the spinner

40
of
23
Spinner
 Spinner sp;

 sp=(Spinner)findViewById(int i); //initialization of Spinner object.


 // “i” is an unique integer in R.java file
 Methods:

• sp.setAdapter(ArrayAdapter adapter)
 //sets an adapter, which has list of items that
has to be displayed inside spinner.
• sp.setOnItemSelected();
 // sets a listener whenever an item is selected from
spinner.
41
of
23
Progress Bar
•  In Android, progress bar is useful to tell user that the task
takes longer time to finish.

• Properties:
• Height // progress bar height(y-size)
• Width // progress bar width(x-size)
• Visibility // used to display or hide the progress bar
• Progress // defines the default progress for the progress bar
• Max // defines the maximum progress for the component

42
of
23
ProgressBar
 ProgressBar pbar;

 pbar=(ProgressBar)findViewById(int i); //initialization of progress bar


object.
 // “i” is an unique integer in R.java file
 Methods:

• pbar.setProgress(int i) //sets a progress for the component, value of “i”


can be from “0” to max.

43
of
23
ImageView
• ImageView in android is used to display images.

• Properties:
• Height // progress bar height(y-size)
• Width // progress bar width(x-size)
• Visibility // used to display or hide the progress bar
• source // defines the source location of image that has to be
displayed

44
of
23
ImageView
 ImageView iview;

 iview=(ImageView)findViewById(int i); //initialization of image view object.


 // “i” is an unique integer in R.java file
 Methods:

• iview.setImageResource(int i) //sets an image form the drawable folder.

45
of
23
AutoCompleteTextView
• AutoCompleteTextView is similar to EditText except that it shows a
list of completion suggestions automatically while the user is typing.
The list of suggestions is displayed in a drop down menu from which
the user can choose an item to replace the content of the edit box with.

• Properties:
• Height // ACTV height(y-size)
• Width // ACTV width(x-size)
• Visibility // used to display or hide the ACTV

46
of
23
AutoCompleteTextView
AutoCompleteTextView actv;

actv=(AutoCompleteTextView)findViewById(int i);

//initialization of ACTV object, “i” is an unique integer in R.java file

Methods:

• actv.setAdapter(ArrayAdapter adapter)

 //sets an adapter, which has list of


items that has to be displayed inside ACTV.
• actv.setOnItemClickListener();

47 // sets a listener whenever an item is selected from ACTV.


of
23
Android - Event Handling
Events are a useful way to collect data about a user's
interaction with interactive components of Applications.
Event Listeners − An event listener is an interface in the View
class that contains a single callback method. These methods will be
called by the Android framework when the View to which the
listener has been registered is triggered by user interaction with the
item in the UI.
Event Listeners Registration − Event Registration is the process
by which an Event Handler gets registered with an Event Listener
so that the handler is called when the Event Listener fires the event.
Event Handlers − When an event happens and we have registered
an event listener for the event, the event listener calls the Event
Handlers, which is the method that actually handles the event.
Intents
• Intents are asynchronous messages which allow Android components to request
functionality from other components of the Android system.
 Ex: An Activity can send Intents to Android System to start another
Activity.
• Intents can be used to signal to the Android system that a certain event has
occurred, other components in Android can register to this event and will get
notified.
• Intent can also contain data. This data can be used by the receiving component.
 Ex: your application can calls via Intent a browser component. As data it
may send the URL to the browser component.
49 • Android supports explicit and implicit Intents.
of
10
Explicit Intents
• Explicit Intents explicitly defines the component which should be called by the
Android system, by using the Java class as identifier.
 Intent i = new Intent(this, ActivityTwo.class);
 i.putExtra("Value1", "This value one for ActivityTwo ");
 i.putExtra("Value2", "This value two ActivityTwo");
 startActivity(i);
 If that Intent is correctly send to the Android system and the class is accessible,

it will start the associated class.


• Explicit Intents are typically used within on application as the classes in an
application are controlled by the application developer.
50
of
10
Implicit Intents
• Implicit Intents specify the action which should be performed and optionally
an URI which should be used for this action.

 Implicit Intents do not directly specify the Android components which


should be called.
 The following code shows an implicit intents
 /*
 Intent intent = new Intent( Intent.ACTION_VIEW, Uri.
Parse("http://www.google.com"));
 */
• If these Intents are send to the Android system it searches for all components
which are registered for the specific action and the data type.

51
of
10
Data Transfer

• Implicit Intents:
 An Implicit intents contains action and optionally the URI, this data can be
obtained by using getData (), getAction () methods.
• Explicit and implicit Intents can also contain additional data. This data can be
filled by the component which creates the Intent. It can get extracted by the
component which receives the Intent, putExtra () method is used to add data.
 Ex: intent.putExtra (key, value);
 value can be anything like String, primitive data type, Bundle,
Parceable and Serializable.

52
of
10
Data Transfer(Example) cont…

Intent intent = new Intent(Intent.ACTION_SEND);


intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);

The component which receives the Intent can use


the getIntent().getExtras() method call to get the extra data.
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
// Do something with the data
}
53
of
10
Intent Filters
• An IntentFilters specifies the types of Intent that an Activity, Service, or Broadcast
Receiver can respond to.

• An Intent Filter declares the capabilities of a component, It specifies what an


Activity or Service do and what types of broadcasts a Receiver can handle.

• It allows the corresponding component to receive Intents of the declared type.

• Intent Filters are typically defined via the AndroidManifest.xml file. For Broadcast


Receiver it is also possible to define them in coding. An Intent Filters is defined by
its category, action and data filters. It can also contain additional metadata.

• If a component does not define an Intent filter, it can only be called by


explicit Intents.
54
of
10
Register your Activity as Browser
• The following code will register an Activity for the Intent which is triggered
when someone wants to open a webpage.

 <activity android:name=".BrowserActivitiy"
 android:label="@string/app_name">
 <intent-filter>
 <action android:name="android.intent.action.VIEW" />
 <category android:name="android.intent.category.DEFAULT" />
 <data android:scheme="http"/>
 </intent-filter>
 </activity>

55
of
10
Menus
• Menus are a common user interface component in many types of applications,
which provides a familiar and consistent user experience.

 Option Menus:
• The ’option menu’ is the primary collection of menu items for an activity. It's
where you should place actions that have a global impact on the app, such as
"Search," "Compose email," and "Settings.“
• Options are independent from focus.
• Avoid using it for navigation.
• Use it for Things like:
• Refresh
• Settings
• Logout
• Sort
56 • Add new item to list.
of
10
Menus cont..
 Context menus:
• A context menu is a floating menu that appears when the user performs a long-
click on an element. It provides actions that affect the selected content or
context frame.
• Shortcuts only, these actions should be available on the main interface too (i.e.
on the detail page for that item)

57
of
10
Android - Styles and Themes
A style resource defines the format and
look for a UI. A style can be applied to an
individual View (from within a layout file)
or to an entire Activity or application (from
within the manifest file).

You might also like