Presentation is loading. Please wait.

Presentation is loading. Please wait.

Android Programming Lecture 4

Similar presentations


Presentation on theme: "Android Programming Lecture 4"— Presentation transcript:

1 Android Programming Lecture 4
Testing notes Activity, Intent and UI

2 Superclass Constructor Interface Inner class

3 RoadMap and Learning Objectives
Learn to use the basic UI widgets Learn to switch Activities using Explicit Intent

4 UI Development

5 Basic Input Controls Input controls are used to take data from user
Widgets TextView Button CheckBox RadioButton Spinner Text Fields Dialogs

6 Text Fields Text Fields allow users to type text in your application.
Text Fields have different types like: Plain Text Person Name Password Phone Postal Address Multiline Text Time Date Number (Signed/Unsigned) All of the Text Fields mentioned above are merely attributes of EditText

7 Text View TextView is used to display text on screen.
EditText, Button are direct subclasses of TextView. TextView doesn't allow editing in itself It works more like a label

8 Buttons Buttons allows user to perform some action.
Android have following button types available, sequence is Control Name (Class Name): Button (Button) Image Button (ImageButton) Toggle Buttons (ToggleButton) Radio Buttons (RadioButton) All buttons have different classes and XML tags to represent them unlike the Text Fields (That had only one tag i.e. EditText)

9 ImageView ImageView is used to display an image.
Can load images from various sources, e.g., drawables/content providers. Various other display options available like scaling & tinting.

10 R.java R.java: hook the resources and java by providing each resource item an ID Reference a resource in Java codes <package_name>: name of the package in which the resource is located (not required when referencing resources from your own package). <resource_type>: resource type. <resource_name>: the resource filename without the extension or the android:name attribute value in the XML element. [<package_name>.]R.<resource_type>.<resource_name> findViewById(R.id.***): identify a view on XML by its id setContentView(R.layout.***): apply the layout for the content view

11 Demo

12 Create a project, and open the layout xml file to make the layout as follows.
TextView EditText Button

13 Create an id for the Button, EditText and TextView, respectively.
This is by specifying the android:id attribute, with formate You can arbitrarily name the id, but make sure that the id is unique

14 Open the MainActivity. java file in the java directory
Open the MainActivity.java file in the java directory. The codes look like below. This is created automatically by the template. You may have more codes over there. If that is the case, no worries. You probably just adopt another template and it is also going to work. In the next slides, we are going to elaborate on the codes.

15 This defines a package, and include your MainActivity class in the package.
My project is named as EditGreeting. So the package name is com.example.editgreeting. You may have different package name here as you use another project name. Can you roughly guess the directory of your MainActivity.java file based on the package name? Do you have an idea why we use a reversed order of the organization for the package name?

16 This imports an package, which define the Activity class
This imports an package, which define the Activity class. You can find the source file in “your ADT directory” \sdk\sources\android-22\android\app

17 This defines a package, and include your MainActivity class in the package.
Can you roughly guess the directory of your MainActivity.java file based on the package name? This imports an package, which define the Activity class. You can find the source file in “your ADT directory” \sdk\sources\android-22\android\app Declare a class

18 This defines a package, and include your MainActivity class in the package.
Can you roughly guess the directory of your MainActivity.java file based on the package name? This imports an package, which define the Activity class. You can find the source file in “your ADT directory” \sdk\sources\android-22\android\app Declare a class Declare the inheritance

19 This defines a package, and include your MainActivity class in the package.
Can you roughly guess the directory of your MainActivity.java file based on the package name? This imports an package, which define the Activity class. You can find the source file in “your ADT directory” \sdk\sources\android-22\android\app Declare a class Declare the inheritance Specify the superclass

20 Adopt the activity_main.xml as the layout
Java use annotation to indicate that the method is created by overriding. When we use this annotation for a method, it tells compiler that we are trying to override a superclass method, and enable the compiler to double check it for us if the method is indeed defined in the superclass. You can consider the onCreate method to be the entry point which is called first by the system in an app. Adopt the activity_main.xml as the layout

21 Java use the @Override annotation to indicate that the method is created by overriding.
You can consider the onCreate method to be the entry point which is called first by the system in an app.

22 Create three variables for your MainActivity class
Create three variables for your MainActivity class. They represents the widgets in your layout which are you going to use later You get the error, because the compiler does not know what EditText, TextView and Button mean. You have to explicitly specify the definition of those classes

23 The needed libraries are automatically imported
Create three variables for your MainActivity class. They represents the widgets in your layout which are you going to use later

24 Input this line of codes.
The purpose of this line is to glue the EditText widget you created in the layout with an object in the Java code. This is by using the method findViewById(int id_of_the_view) In this way, we are able to reference the widgets using Java codes

25 Type casting to ensure that the returned result of findViewById belong to the desired data type

26 Input another line of code, which associates the TextView widget in the layout with a TextView object t in the codes

27 Can you add the codes for the button in the same manner as we do for TextView and EditText? This is because that we are also going to use the Button in the Java codes later.

28 The codes look like this

29 Your codes would look like

30 Add the codes like this

31 You may encounter some error on the codes
You may encounter some error on the codes. This is because that the compiler does not know what OnClickListener interface is.

32 Call the setOnClickListener method of the button b
The method enables the button to capture the user’s click operation on the button

33 The method MyButtonOnClickListener () is the constructor of the class.
Call the setOnClickListener method of the button b The method enables the button to capture the user’s click operation on the button The method MyButtonOnClickListener () is the constructor of the class.

34 Define the MyButtonOnClickListener class
indicate that the class adopts the OnClickListener interface

35 Inside the onClick method, input the line of code.
From the name of the method, you can roughly guess that this is to set the text of the TextView t, using the content of the EditText e This is by retrieving the text of e using the method getText(), and then call the setText() method of t

36 By associating the button with the a click listener
By associating the button with the a click listener. The onClick method is called automatically when the listener detect the user’s click operation on the button

37 Run the app in AVD. Input some text in the EditText and click the button to see if this is working.
To summarize: We have created the widgets on the layout, and create an id for each widget We have called the findViewById() method to glue the widget on layout with the Java codes We have set up a class implement the OnClickListener, and apply it to the Button. This allows the button the capture the user’s click operation. We have revised the onClick() method to retrieve the text of the EditText and give it to the TextView

38 Android Studio Hotkeys
Reformat code: CTRL + ALT + L (Win) OPTION + CMD + L (Mac) Quick Fix: Alt + Enter Jump to source: F4

39 View.OnClickListener Defined in android.view.View.OnClickListener
Interface definition for a callback to be invoked when a view is clicked Create an OnClickListener protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button_send); // Create an object of the custom onClickListener YourOnClickListener anOnClickListener = new YourOnClickListener(); // Attach the created onClickListener with the button button.setOnClickListener(anOnClickListener); } class YourOnClickListener implements OnClickListener{ @Override public void onClick(View v) { Refer to for detailed information

40 Using Anonymous Inner Class
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button_send); // Create an object of the custom onClickListener YourOnClickListener anOnClickListener = new YourOnClickListener(); // Attach the created onClickListener with the button button.setOnClickListener(anOnClickListener); } class YourOnClickListener implements OnClickListener{ @Override public void onClick(View v) { Using Anonymous Inner Class protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button_send); // Using the anonymous inner class button.setOnClickListener(new OnClickListener() { // Create the anonymous inner class @Override public void onClick(View v) { } });

41 Using UI Widgets: Step 1 1. Create in XML layout Create an id using
Specify the necessary attributes android:layout_width="match_parent" android:layout_height="match_parent“ <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="30dp" android:text="Sea" /> <AnalogClock android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_gravity="center" />

42 Using UI Widgets: Step 2 Associate Layout with Java,
create an object of the corresponding class that the widget belongs to Associate the object in Java and the widget in XML using the method findViewById(android.R.id.***) Type casting Return a generic View object Data Type id Button myButton = (Button) findViewById(R.id.button); ImageView myImage = (ImageView) findViewById(R.id.imageView); LinearLayout myLayout = (LinearLayout) findViewById(R.id.appLayout);

43 Using UI Widgets: Step 3 3. Use the widget in Java
Access and configure the UI with getXXX() and setXXX() Associate the object with necessary Event Handler SeekBar aSeekBar = new SeekBar(this); aSeekBar.setMax(100); aSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } });

44 SeekBar and ProgressBar
Class Reference:

45 SeekBar.OnSeekBarChangeListener
Listener that receives notifications of changes to the SeekBar's progress level Implement three methods onProgressChanged(SeekBar seekBar, int progress, boolean fromUser): Notification that the progress level has changed onStartTrackingTouch(SeekBar seekBar): Notification that the user has started a touch gesture onStopTrackingTouch(SeekBar seekBar): Notification that the user has finished a touch gesture. Tutorial:

46 Check Box Allows users to select one or more options from the set
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="78dp" android:text="Android" /> android:layout_marginTop="20dp" android:text="iOS" /> android:text="Windows" /> android:text="RIM" /> Class Reference:

47 Demo Video Tutorial: Topic #10 on Checkbox: Create a note named “Checkbox” and copy the codes on Evernote

48 Toast A toast provides simple feedback about an operation in a small popup Context: Interface to global information about an application environment Text: text to show Duration: How long to display the message Context context = getApplicationContext(); // Content of the text in the Toast String text = "Hello toast!"; // How long to display the message int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); For more information about Context:

49 Action Bar The action bar provides several key functions:
Provides a dedicated space for giving your app an identity and indicating the user's location in the app. Makes important actions prominent and accessible in a predictable way (such as Search). Supports consistent navigation and view switching within apps (with tabs or drop-down lists).

50 public class MainActivity extends ActionBarActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is // present. // Load the main.xml file defined in res/menu folder getMenuInflater().inflate(R.menu.main, menu); return true; public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button int id = item.getItemId(); if (id == R.id.action_settings) { return super.onOptionsItemSelected(item);

51 Demo Video Tutorial: Topic #29 and #30 on Action Bar: Create a note named “Action Bar” and copy the codes on Evernote

52 AlertDialog Title This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you need to state a simple message or question (such as the dialog in figure 1), you don't need a title. Content area This can display a message, a list, or other custom layout. Action buttons There should be no more than three action buttons in a dialog.

53 // 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); // 2. Chain together various setter methods to set the dialog // characteristics builder.setMessage("Example of Alert Dialog") .setTitle("Alert Dialog") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // User clicked OK button } }) .setNegativeButton("Cancel",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog }); // Set other dialog properties // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); // 4. Show dialog dialog.show();

54 Demo Video Tutorial: Topic #12 # Android Alert Dialog Example: Create a note named “Alert Dialog” and copy the codes on Evernote

55 Activity

56 What is an Activity Activities encapsulate “a single, focused thing that the user can do.” Activity provides the user a screen with which the user can interact. Each activity is assigned a window Window content is implemented in subordinate Views

57 Multiple Activities One activity can start another activity
An Application always starts with a main activity An application can have multiple activities that the user moves in and out of

58 Monique Gorge Selina Adam About Activity Main Activity Game Activity
Score Activity About Activity Monique Gorge Selina Adam User

59 Monique // in Monique.java public class Monique extends Activity {
} // Variables (attributes) that the Monique class; // Methods (behaviours) of the Monique class; Monique

60 Intent Monique Gorge public class Gorge extends Activity { }
// in Monique.java public class Monique extends Activity { } // in Gorge.java public class Gorge extends Activity { } // Variables (attributes) that the Monique class; // Methods (behaviours) of the Monique class; // Variables (attributes) that the Gorge class; // Methods (behaviours) of the Gorge class; Intent Monique Gorge

61 Intent Intent Intent public class Monique extends Activity {
// variables and methods of Monique } public class Gorge extends Activity { // variables and methods of Gorge } public class Selina extends Activity { // variables and methods of Selina } public class Adam extends Activity { // variables and methods of Adam } Intent Intent Intent

62 public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) { } protected void onStart() { protected void onResume() { protected void onPause() { protected void onStop() { protected void onRestart() { protected void onDestroy() {

63 Lifecycle of an Activity
An activity's lifecycle is a set of states and methods performed at each state Get prepared to work, start working, transfer the work to others … When the current state of an activity changes, the Android OS notifies the activity of that change The Android developer manages the activity's lifecycle by implementing the standard callback methods that are called on the activity object when its state changes Callback implementation is the only leverage the developer has over activities

64 The three callbacks, onCreate(), onStart(), onResume(), are called in sequence, when creating a new instance of an activity. After sequence of callbacks complete, the activity reaches the Resumed state where the user can interact with the activity onStart(): Called when the activity is about to become visible onResume(): Called when the activity is visible and will start interacting with the user.

65 Pausing & Resuming an Activity
When the foreground activity is obstructed by other visual components, e.g., a semi-transparent activity opens such as dialog, onPause() is called and the activity waits in the Pause state. If the user returns to the activity while it’s still paused, the system calls onResume()

66 Pausing: onPause() We usually use the onPause() callback to:
Stop animations or other ongoing actions that could consume CPU. Commit unsaved changes (such as a draft ) Release system resources, such as handles to sensors (like GPS), or any resources that may affect battery life. @Override public void onPause() { // Always call the superclass method first super.onPause(); // Release the Camera because we don't need it when paused // and other activities might need to use it. if (mCamera != null) { mCamera.release() mCamera = null; } Operations in onPause() must be kept simple in order to allow for a speedy transition to the user’s next destination

67 Stoping & Restarting an Activity
When the activity is fully-obstructed and not visible, the system calls onStop() to stop the activity. If the user returns while the activity is stopped, the system calls onRestart(), quickly followed by onStart() and onResume().

68 There are a few of key scenarios in which activity is stopped and restarted:
1. User opens the Recent Apps window and switches from the app to another app. If the user returns to the app from the Home screen launcher icon or the Recent Apps window, the activity restarts. 2. When a new Activity is launched. The current activity is stopped when the second activity is created. 3. The user receives a phone call while using your app on his or her phone. We should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database

69 Summary: Activity’s Lifetime

70 Demo 1 Download the codes on Cloud Deakin/Resource/Week 4

71 Demo 2 Video Tutorial: Topic #5 and #6 on the Life Cycle of Activity:

72 Intent Intent Monique Gorge

73 What is Intent Intents are messages which allow Android components to request functionality from other components of the Android system. Intent are used for requesting information, computation, or event signalling All intents objects are instances of android.content.Intent Intent

74 Start an Activity with Intent
Explicit Intent Activity 1 Activity 2 Intent Intent anIntent = new Intent(this, Activity2.class); startActivity(anIntent); Activity 1 Activity 2 Intent Intent AnotherIntent = new Intent(this, Activity1.class); startActivity(AnotherIntent);

75 Anonymous inner class

76 Activity A creates an Intent with an Action description and passes it to startActivity().
The Android System searches all apps for an intent filter that matches the intent. When a match is found, the system starts the matching activity (Activity B) by invoking its onCreate() method and passing it the Intent.

77 Demo Video Tutorial: Topic #13 How to Start New Activity On Button Click via Intent : Create a note named “Explicit Intent” and copy the codes on Evernote

78 Manifest.xml

79 What is Android Manifest File
Every application must have an Android Manifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system. information the system must have before it can run any of the application's code.

80 Tags in Manifest xml File
<action> <activity> <activity-alias> <application> <category> <data> <grant-uri-permission> <instrumentation> <intent-filter> <manifest> <meta-data> <permission> <permission-group> <permission-tree> <provider> <receiver> <service> <uses-configuration> <uses-library> <uses-permission> <uses-sdk>

81 AndroidManifest.xml Applications should declare everything needed on the the AndroidManifest.xml file … One AndroidManifest.xml for application .. What's contained in it? Permissions Hardware and Software resources used by the Application Activities Intent-filters


Download ppt "Android Programming Lecture 4"

Similar presentations


Ads by Google