Android Programming Lecture 4

Slides:



Advertisements
Similar presentations
CE881: Mobile and Social Application Programming Simon M. Lucas Menus and Dialogs.
Advertisements

Android 02: Activities David Meredith
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
User Interface Classes.  Design Principles  Views & Layouts  Event Handling  Menus  Dialogs.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Filip Debelić What is it? Android is a mobile operating system (OS) based on the Linux kernel and currently developed by Google Android,
ANDROID PROGRAMMING MODULE 1 – GETTING STARTED
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Android Development (Basics)
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
Better reference the original webpage :
Android development the first app. Andoid vs iOS which is better? Short answer: neither Proponents on both sides For an iOS side, see this article on.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
Favorite Twitter® Searches App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
Chapter 2: Simplify! The Android User Interface
Chapter 5 Creating User Interfaces GOALS and OBJECTIVES Begin our application by creating our user interface. More than one way to create a user interface.
Chapter 2 The Android User Interface. Objectives  In this chapter, you learn to:  Develop a user interface using the TextView, ImageView, and Button.
INTRODUCTION TO ANDROID. Slide 2 Application Components An Android application is made of up one or more of the following components Activities We will.
SpotOn Game App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
Programming Mobile Applications with Android September, Albacete, Spain Jesus Martínez-Gómez.
Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml.
Android Boot Camp for Developers Using Java, Comprehensive: A Guide to Creating Your First Android Apps Chapter 2: Simplify! The Android User Interface.
Handling View Events. Open the *MainActivity.java* which is the Activity that hosts the layout in "activity_main.xml". The setContentView method inside.
Styles, Dialog Boxes, and Menus. Styles Allow creation of a common format – placed in res/values/styles.xml – file name is incidental Can be applied.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
MOBILE COMPUTING D10K-7D02 MC05: Android UI Design Dr. Setiawan Hadi, M.Sc.CS. Program Studi S-1 Teknik Informatika FMIPA Universitas Padjadjaran.
Events. Slide 2©SoftMoore Consulting Events Events are generated when a user interacts with the view objects of an application. Examples –button clicked–
ANDROID LAYOUTS AND WIDGETS. Slide 2 Introduction Parts of the Android screen Sizing widgets and fonts Layouts and their characteristics Buttons, checkboxes.
Introduction to Android Programming
Menus. Menus are a common user interface component in many types of applications. The options menu is the primary collection of menu items for an activity.
Chapter 2: Simplify! The Android User Interface
Lab7 – Appendix.
Introduction to android
Android Programming - Features
Mobile Applications (Android Programming)
Mobile Application Development BSCS-7 Lecture # 2
Android Application Development 1 6 May 2018
Activity and Fragment.
Mobile Application Development BSCS-7 Lecture # 9
Android – Event Handling
Mobile Application Development Chapter 3 [Using Eclipse Android Studio for Android Development] IT448-Fall 2017 IT448- Fall2017.
Activities, Fragments, and Events
Mobile Application Development BSCS-7 Lecture # 8
MAD.
Activities and Intents
Anatomy of an Android App and the App Lifecycle
Android Widgets 1 7 August 2018
Creation of an Android App By Keith Lynn
Mobile Application Development Chapter 4 [Android Navigation and Interface Design] IT448-Fall 2017 IT448- Fall2017.
The Android Activity Lifecycle
CIS 470 Mobile App Development
Anatomy of an Android App and the App Lifecycle
CMPE419 Mobile Application Development
BMI Android Application will take weight and height from the users to calculate Body Mass Index (BMI) with the information, whether user is underweight,
Android Developer Fundamentals V2
Activities and Intents
HNDIT2417 Mobile Application Development
CIS 470 Mobile App Development
Activities and Intents
Android Project Structure, App Resources and Event Handling
SE4S701 Mobile Application Development
CMPE419 Mobile Application Development
Activities and Fragments
Android Development Tools
Activities, Fragments, and Intents
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Android Programming Lecture 4 Testing notes Activity, Intent and UI

Superclass Constructor Interface Inner class

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

UI Development

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

Text Fields Text Fields allow users to type text in your application. Text Fields have different types like: Plain Text Person Name Password Email Phone Postal Address Multiline Text Time Date Number (Signed/Unsigned) All of the Text Fields mentioned above are merely attributes of EditText http://developer.android.com/guide/topics/ui/controls/text.html

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 http://developer.android.com/reference/android/widget/TextView.html

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) http://developer.android.com/guide/topics/ui/controls/button.html

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.

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

Demo

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

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

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.

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?

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

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

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

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

Adopt the activity_main.xml as the layout Java use the @Override 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. http://www.journaldev.com/817/overriding-methods-in-java-always-use-override-annotation 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 http://developer.android.com/reference/android/app/Activity.html

Java use the @Override annotation to indicate that the method is created by overriding. http://www.javapractices.com/topic/TopicAction.do?Id=223 You can consider the onCreate method to be the entry point which is called first by the system in an app.

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

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

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

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

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

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.

The codes look like this

Your codes would look like

Add the codes like this

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.

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. 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.

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

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

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

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

Android Studio Hotkeys Reformat code: CTRL + ALT + L (Win) OPTION + CMD + L (Mac) Quick Fix: Alt + Enter Jump to source: F4 https://developer.android.com/sdk/installing/studio-tips.html

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 http://developer.android.com/guide/topics/ui/ui-events.html for detailed information

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) { } });

Using UI Widgets: Step 1 1. Create in XML layout Create an id using Specify the necessary attributes android:id="@+id/newID" android:layout_width="match_parent" android:layout_height="match_parent“ … <Button android:id="@+id/buttonSea" 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:id="@+id/analogClock" android:layout_marginTop="40dp" android:layout_gravity="center" />

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);

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) { } … });

SeekBar and ProgressBar http://developer.android.com/design/building-blocks/seek-bars.html http://developer.android.com/design/building-blocks/progress.html Class Reference: http://developer.android.com/reference/android/widget/SeekBar.html http://developer.android.com/reference/android/widget/ProgressBar.html

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: https://www.youtube.com/watch?v=l5FrTkGoeX8 http://developer.android.com/reference/android/widget/SeekBar.OnSeekBarChangeListener.html

Check Box Allows users to select one or more options from the set android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="78dp" android:text="Android" /> android:id="@+id/checkBox2" android:layout_marginTop="20dp" android:text="iOS" /> android:id="@+id/checkBox3" android:text="Windows" /> android:id="@+id/checkBox4" android:text="RIM" /> Class Reference: http://developer.android.com/reference/android/widget/CheckBox.html

Demo Video Tutorial: Topic #10 on Checkbox: https://www.youtube.com/playlist?list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E Create a note named “Checkbox” and copy the codes on Evernote

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: http://www.simplecodestuffs.com/what-is-context-in-android/

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). http://developer.android.com/guide/topics/ui/actionbar.html

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);

Demo Video Tutorial: Topic #29 and #30 on Action Bar: https://www.youtube.com/playlist?list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E Create a note named “Action Bar” and copy the codes on Evernote

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. http://developer.android.com/guide/topics/ui/dialogs.html

// 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();

Demo Video Tutorial: Topic #12 # Android Alert Dialog Example: https://www.youtube.com/playlist?list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E Create a note named “Alert Dialog” and copy the codes on Evernote

Activity

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

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

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

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

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

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

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() { http://developer.android.com/reference/android/app/Activity.html

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

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.

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()

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 email) 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

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().

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

Summary: Activity’s Lifetime

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

Demo 2 Video Tutorial: Topic #5 and #6 on the Life Cycle of Activity: https://www.youtube.com/playlist?list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E

Intent Intent Monique Gorge

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

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);

Anonymous inner class

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.

Demo Video Tutorial: Topic #13 How to Start New Activity On Button Click via Intent : https://www.youtube.com/playlist?list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E Create a note named “Explicit Intent” and copy the codes on Evernote

Manifest.xml

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.

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> http://developer.android.com/guide/topics/manifest/manifest-intro.html

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