Android Basic Course
Module 3: Application Basic
Department of Software Engineering, Faculty of Information Technology, University of Science Ho Chi Minh City, Viet Nam
.
2012 University of Science HCM City
Android Basic Course
Objectives
After completing this module, you will have learned:
About project structure How resources are used How Different Resources
XML Files Some main content of the AndroidManifest.xml file About Fundamental Android UI Design About XML-based layouts About Handling events by using event handlers or listeners Are Referenced from Within Java and
2012 University of Science HCM City
Android Basic Course
Contents
Understanding project structure How different resources are referenced
Java and XML Files The Android application manifest Fundamental Android UI Design Overview XML-based layouts Handling events by using event handlers Handling events by using event listeners
from within
2012 University of Science HCM City
Android Basic Course
Understanding project structure
contains java source files is generated when res folder is modified is selected platform to build the application is application package that will be installed on emulators or real devices are image resources
describes UI components describes string constant values
is an application configuration file
. 4
2012 University of Science HCM City
Android Basic Course
How Different Resources Are Referenced from Within Java and XML Files
Resource res/layout/main.xml res/drawable-hdpi/icon.png @+id/home_button <string name = hello>
Reference in Java R.layout.main R.drawable.icon R.id.home_button R.string.hello
Reference in XML @layout/main @drawable/icon @id/home_button @string/hello
2012 University of Science HCM City
Android Basic Course
R.java file is generated by resources
2012 University of Science HCM City
Android Basic Course
Different resources are referenced from within Manifest file
2012 University of Science HCM City
Android Basic Course
Using R.java file
setContentView(R.layout.main); mTitleText = (EditText) findViewById(R.id.title); mBodyText = (EditText) findViewById(R.id.body);
2012 University of Science HCM City
Android Basic Course
The Android application manifest
Each
Android project includes a manifest le, AndroidManifest.xml, stored in the root of the project hierarchy. The manifest lets you dene the structure and metadata of your application, its components, and its requirements.
2012 University of Science HCM City
Android Basic Course
Android application components and declaring requirements
Java Base Class Activity Service ContentProvider BroadcastReceiver Functionality Focus thing a user can do Background Process Store and retrieve data Receive message Examples Edit a note, play a game Play music, update weather icon Open a phone contact Trigger alarm upon event
The Android Application Manifest file includes nodes for
each of the components (Activities, Services, Content Providers, and Broadcast Receivers) that make up your application and, using Intent Filters and Permissions, determines how they interact with each other and with other applications.
. 10
2012 University of Science HCM City
Android Basic Course
Some main content of the AndroidManifest.xml
Manifest Root document
Version Code Property Version Name Property Use-SDK Node Use-Permission Nodes Application Node
Min SDK Version Max SDK Version Target SDK Version
Activity Nodes Service Nodes Content Provider Nodes Broadcast Receiver Nodes
Using Intent Filters and Permissions
11
2012 University of Science HCM City
Android Basic Course
The AndroidManifest.xml of Hello World Application
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloandroid" android:versionCode="1" Each upload to Market requires versionCode increment android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> Specifies icon for launching app <application android:icon="@drawable/ic_launcher" Specifies icon for launching app android:label="@string/app_name" > <activity Specifies activity to be launched at startup android:label="@string/app_name" android:name=".HelloAndroid" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> Using Intent Filters and Permission </manifest>
. 12
2012 University of Science HCM City
Android Basic Course
The AndroidManifest.xml of Contact Manager Application
<?xml version="1.0" encoding="utf-8"?> Security permissions requested from user on install <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.contactmanager" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="5" android:targetSdkVersion="5" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <application android:label="@string/app_name" android:icon="@drawable/icon"> <activity android:name=".ContactManager" 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="ContactAdder" android:label="@string/addContactTitle"> </activity> </application> </manifest> Activity Node
. 13
2012 University of Science HCM City
Android Basic Course
The AndroidManifest.xml of Note Pad Application
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.notepad" > <uses-sdk android:minSdkVersion="11" /> <application android:icon="@drawable/app_notes" android:label="@string/app_name" > <provider android:authorities="com.google.provider.NotePad" android:exported="false" android:name="NotePadProvider" > <grant-uri-permission android:pathPattern=".*" /> </provider> <activity Content Provider Node </activity> </application> </manifest>
. 14
2012 University of Science HCM City
Android Basic Course
The AndroidManifest.xml of Random Music Player Application
<application <service android:exported="false" android:name=".MusicService" > <intent-filter > <action android:name="com.example.android.musicplayer.action.TOGGLE_PLAYBACK" /> <action android:name="com.example.android.musicplayer.action.PLAY" /> <action android:name="com.example.android.musicplayer.action.PAUSE" /> <action android:name="com.example.android.musicplayer.action.SKIP" /> <action android:name="com.example.android.musicplayer.action.REWIND" /> <action android:name="com.example.android.musicplayer.action.STOP" /> </intent-filter> <intent-filter > <action android:name="com.example.android.musicplayer.action.URL" /> <data android:scheme="http" /> </intent-filter> </service>
Service Node
. 15
2012 University of Science HCM City
Android Basic Course
The AndroidManifest.xml of Random Music Player Application
<receiver android:name=".MusicIntentReceiver" > <intent-filter > <action android:name="android.media.AUDIO_BECOMING_NOISY" /> </intent-filter> <intent-filter > <action android:name="android.intent.action.MEDIA_BUTTON" /> </intent-filter> </receiver> </application> Broadcast Receiver Node
16
2012 University of Science HCM City
Android Basic Course
Fundamental Android UI Design
Views are the base class for all visual interface elements
(commonly known as controls or widgets). All UI controls, including the layout classes, are derived from View. View Groups are extensions of the View class that can contain multiple child Views. Extend the ViewGroup class to create compound controls made up of interconnected child Views. The ViewGroup class is also extended to provide the layout managers that help you lay out controls within your Activities. Activities described in the previous modules, represent the window, or screen, being displayed. Activities are the Android equivalent of Forms. To display a user interface you assign a View (usually a layout) to an Activity.
. 17
2012 University of Science HCM City
Android Basic Course
High-level diagram class of the Android View API
Activity View
ViewGroup
Android built-in single view classes
Android built-in view container classes
Android built-in layout classes
18
2012 University of Science HCM City
Android Basic Course
A part of a class diagram of the Android View API
19
2012 University of Science HCM City
Android Basic Course
A subset of methods in the base Android View API
setBackgroundColor(int color) setBackgroundDrawable(Drawable d) setClickable(boolean c) setFocusable(boolean f) setLayoutParams(ViewGroup.LayoutParams l) setMinimumHeight(int minHeight) setMinimumWidth(int minWidth) setOnClickListener(OnClickListener l) setOnFocusChangeListener(OnFocusChangeListener l) setPadding(int left, int right, int top, int bottom)
20
2012 University of Science HCM City
Android Basic Course
Using XML-Based Layouts
While
it is technically possible to create and attach widgets to your activity purely through Java code, the more common approach is to use an XML-based layout file. Dynamic instantiation of widgets is reserved for more complicated scenarios, where the widgets are not known at compile time (e.g., populating a column of radio buttons based on data retrieved from the Internet)
XML based layout file is defined here
21
2012 University of Science HCM City
Android Basic Course
What Is an XML-Based Layout?
An XML-based layout is a specification of widgets relationships to each otherand to containersencoded in XML format. Android considers XML-based layouts to be resources, and as such, layout files are stored in the res/layout directory inside your Android project Each XML file contains a tree of elements specifying a layout of widgets and containers that make up one View. The attributes of the XML elements are properties, describing how a widget should look or how a container should behave. Androids SDK ships with a tool (aapt) that uses the layouts. Of particular importance to you as a developer is that aapt generates the R.java source file within your projects gen/ directory, allowing you to access layouts and widgets within those layouts directly from your Java code
22
2012 University of Science HCM City
Android Basic Course
Why Use XML-Based Layouts?
Most
everything you do using XML layout files can be achieved through Java code. For example, you could use setTypeface() to have a button render its text in bold, instead of using a property in an XML layout. Dynamic instantiation of widgets is reserved for more complicated scenarios, where the widgets are not known at compile time. Using XML-based layout does have the advantage of helping to ease the transition to Android from any other XML-centered view description language.
Ex: XAML, Adobes Flex, GWT, XUI, etc.
23
2012 University of Science HCM City
Android Basic Course
XLM-based layout example
<?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/button" android:text="" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
The + after the @ in the id string indicates that the id should be automatically created as a resource if it does not already exist.
24
2012 University of Science HCM City
Android Basic Course
Loading XML-based layout resources
package com.commonsware.android.layouts; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.util.Date; public class NowRedux extends Activity implements View.OnClickListener { Button btn; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); btn=(Button)findViewById(R.id.button); btn.setOnClickListener(this); updateTime(); }
<?xml version="1.0" encoding="utf-8"?> <Button android:id="@+id/button android:layout_height="fill_parent"/>
public void onClick(View view) { updateTime(); }
private void updateTime() { btn.setText(new Date().toString()); } }
25
2012 University of Science HCM City
Android Basic Course
Handling events by using event handlers
public class ExampleActivity extends Activity implements OnClickListener { protected void onCreate(Bundle savedValues) { ... Button button = (Button)findViewById(R.id.corky); Button button = (Button)findViewById(R.id.sketchy); ... button.setOnClickListener(this); } // Implement the OnClickListener callback public void onClick(View v) { switch(v.getId()) { case R.id.corky: // do something when the button is clicked case R.id.sketchy: // do something when the button is clicked } ... }
26
2012 University of Science HCM City
Android Basic Course
Handling events by using event listeners
protected void onCreate(Bundle savedValues) { ... // Capture our button from layout Button button = (Button)findViewById(R.id.corky); // Register the onClick listener with the implementation above button.setOnClickListener(new OnClickListener() { public void onClick(View v) { // do something when the button is clicked }
});
... }
27
2012 University of Science HCM City
Android Basic Course
Handling events by using event listeners
// Create an anonymous implementation of OnClickListener private OnClickListener mCorkyListener = new OnClickListener() { public void onClick(View v) { // do something when the button is clicked } };
protected void onCreate(Bundle savedValues) { ... // Capture our button from layout Button button = (Button)findViewById(R.id.corky); // Register the onClick listener with the implementation above button.setOnClickListener(mCorkyListener); ... }
. 28
2012 University of Science HCM City
Android Basic Course
Handling events by using event listeners
<Button ... android:onClick="someMethod" ... />
public void someMethod(View theButton) { // do something useful here }
29
2012 University of Science HCM City
Android Basic Course
Questions or Discussions
How
many kinds of resources are there in an Android Application? What are they? How are resources used? Why should we use string values in string.xml file rather than use them directly?
Should use tv.setText(R.string.app_name); Shouldnt use tv.setText("Hello, Android"); Why use xml-based layouts?
Ex:
30
2012 University of Science HCM City
Android Basic Course
References & Further Readings
List of Files for an Android Application Print Messages to a Log File
gging
http://developer.android.com/resources/faq/commontasks.html#fi
lelist
http://developer.android.com/resources/faq/commontasks.html#lo http://developer.android.com/resources/faq/commontasks.html#h
andle
Getting a Handle to a Screen Element
Listening for Button Clicks
stening
http://developer.android.com/resources/faq/commontasks.html#li
31
2012 University of Science HCM City
Android Basic Course
References & Further Readings
The Android Developers Cookbook Building Applications with the Android SDK, James Steele,
Nelson To, Addison-Wesley Professional Publishing (2011) Android Application Overview, Chapter 2
32
2012 University of Science HCM City
Android Basic Course
References & Further readings
Professional
Application
Reto Meier, Wiley Publishing (2010)
Android 2 Development,
Fundamental
Chapter 4
Android UI Design,
33
2012 University of Science HCM City
Android Basic Course
References & Further Readings
Beginning
Using
Mark Murphy, Apress Publishing (2011)
Android
3,
XML-Based Layouts, Chapter 3
34
2012 University of Science HCM City