Android Basic Course © 2012 University of Science – HCM City . M.Sc. Bui Tan Loc [email protected] Department of Software Engineering, Faculty of Information Technology, University of Science – Ho Chi Minh City, Viet Nam Module 3: Application Basic
Android Basic Course
© 2012 University of Science – HCM City .
M.Sc. Bui Tan Loc
Department of Software Engineering,
Faculty of Information Technology,
University of Science – Ho Chi Minh City, Viet Nam
Module 3: Application Basic
Android Basic Course
© 2012 University of Science – HCM City .
Objectives
• After completing this module, you will have learned: • About project structure
• How resources are used
• How Different Resources Are Referenced from Within Java and 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
2
Android Basic Course
© 2012 University of Science – HCM City .
Contents
• Understanding project structure
• How different resources are referenced from within 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
3
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
How Different Resources Are Referenced from Within Java and XML Files
Resource Reference in Java Reference in XML
res/layout/main.xml R.layout.main @layout/main
res/drawable-hdpi/icon.png R.drawable.icon @drawable/icon
@+id/home_button R.id.home_button @id/home_button
<string name = “hello”> R.string.hello @string/hello
5
Android Basic Course
© 2012 University of Science – HCM City .
R.java file is generated by resources
6
Android Basic Course
© 2012 University of Science – HCM City .
Different resources are referenced from within Manifest file
7
Android Basic Course
© 2012 University of Science – HCM City .
Using R.java file
…
setContentView(R.layout.main); …
mTitleText = (EditText) findViewById(R.id.title); mBodyText = (EditText) findViewById(R.id.body);
…
8
Android Basic Course
© 2012 University of Science – HCM City .
The Android application manifest
• Each Android project includes a manifest file, AndroidManifest.xml, stored in the root of the project hierarchy. The manifest lets you define the structure and metadata of your application, its components, and its requirements.
9
Android Basic Course
© 2012 University of Science – HCM City .
Android application components and declaring requirements
Java Base Class Functionality Examples
Activity Focus thing a user can do Edit a note, play a game
Service Background Process Play music, update weather icon
ContentProvider Store and retrieve data Open a phone contact
BroadcastReceiver Receive message Trigger alarm upon event
10
• 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.
Android Basic Course
© 2012 University of Science – HCM City .
Some main content of the AndroidManifest.xml
• Manifest Root document • Version Code Property
• Version Name Property
• Use-SDK Node •Min SDK Version
•Max SDK Version
• Target SDK Version
• Use-Permission Nodes
• Application Node •Activity Nodes
•Service Nodes
• Content Provider Nodes
• Broadcast Receiver Nodes
Using Intent Filters and Permissions
11
Android Basic Course
© 2012 University of Science – HCM City .
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"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
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>
</manifest>
Each upload to Market requires versionCode increment
Specifies icon for launching app
Specifies icon for launching app
Specifies activity to be launched at startup
Using Intent Filters and Permission
12
Android Basic Course
© 2012 University of Science – HCM City .
The AndroidManifest.xml of Contact Manager Application <?xml version="1.0" encoding="utf-8"?>
<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>
Security permissions requested from user on install
Activity Node
13
Android Basic Course
© 2012 University of Science – HCM City .
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
…
</activity>
…
</application>
</manifest>
Content Provider Node
14
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
High-level diagram class of the Android View API
18
View
ViewGroup
Activity
… …
… …
Android built-in layout classes
Android built-in view container classes
Android built-in single view classes
Android Basic Course
© 2012 University of Science – HCM City .
A part of a class diagram of the Android View API
19
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
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)
21
XML – based layout file is defined here
Android Basic Course
© 2012 University of Science – HCM City .
What Is an XML-Based Layout?
• An XML-based layout is a specification of widgets’ relationships to each other—and to containers—encoded 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.
• Android’s 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 project’s gen/ directory, allowing you to access layouts and widgets within those layouts directly from your Java code
22
Android Basic Course
© 2012 University of Science – HCM City .
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, Adobe’s Flex, GWT, XUI, etc.
23
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
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();
}
public void onClick(View view) {
updateTime();
}
private void updateTime() {
btn.setText(new Date().toString());
}
}
25
<?xml version="1.0" encoding="utf-8"?>
<Button
…
android:id="@+id/button“
…
android:layout_height="fill_parent"/>
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
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
Android Basic Course
© 2012 University of Science – HCM City .
Handling events by using event listeners
<Button
...
android:onClick="someMethod"
...
/>
public void someMethod(View theButton) {
// do something useful here
}
29
Android Basic Course
© 2012 University of Science – HCM City .
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? • Ex:
•Should use tv.setText(R.string.app_name);
•Shouldn’t use tv.setText("Hello, Android");
•Why use xml-based layouts?
30
Android Basic Course
© 2012 University of Science – HCM City .
References & Further Readings
• List of Files for an Android Application • http://developer.android.com/resources/faq/commontasks.html#fi
lelist
• Print Messages to a Log File • http://developer.android.com/resources/faq/commontasks.html#lo
gging
• Getting a Handle to a Screen Element • http://developer.android.com/resources/faq/commontasks.html#h
andle
• Listening for Button Clicks • http://developer.android.com/resources/faq/commontasks.html#li
stening
31
Android Basic Course
© 2012 University of Science – HCM City .
References & Further Readings
• The Android Developer’s Cookbook Building Applications with the Android SDK, James Steele, Nelson To, Addison-Wesley Professional Publishing (2011)
• Android Application Overview, Chapter 2
32
Android Basic Course
© 2012 University of Science – HCM City .
References & Further readings
• Professional Android 2 Application Development, Reto Meier, Wiley Publishing (2010) • Fundamental Android UI Design,
Chapter 4
33