68
Android Introduction Architecture Activities, Lifecycle Development Environment 1

Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Android IntroductionArchitecture

Activities, Lifecycle

Development Environment

1

Page 2: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Why Android?

2

§ Pervasive Mobile Platform- Runs on hundreds of millions of mobile phones, tablets

- World’s most popular & frequently installed mobile OS

- Open Source (minimum-definition).

§ Developer Friendly

- Familiar language (e.g. Java, Kotlin)- Multi-platform support

- Android Studio, IntelliJ support

§ See http://developer.android.com/tools/index.html

Page 3: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Development Environment

3

§ Java JDK - https://adoptopenjdk.net/index.html

§ Android SDK- https://developer.android.com/studio- Included in the Android Studio installation

§ Development Environment- Plan on using IntelliJ or Android Studio - Examples are provided as IntelliJ projects- https://www.jetbrains.com/idea/download

Page 4: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Architecture

5

§ Applications are built in Java (or Kotlin, or C++)- Android compiler generates an Android Package (.apk file), which

contains code, resources etc.- Package is installed using SDK, which sets up environment for that app.

§ Applications run securely in the environment- Android is a Linux environment where every app is a distinct user!- When the app is installed, permissions are set to restrict access

(resources, data).- Every app runs in its own process.- Apps must request access to shares resources (e.g. file system,

camera)

§ As a developer, you create a manifest file in your package that describes how your application should be installed, what permissions it requires.

Page 5: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

6

Page 6: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Setup

7

1. Download and install Java JDK.

2. Download and install Android Studio to get the Android SDK.

3. IntelliJ has an Android plugin that will use the Android SDK. Both IDEs work, but IntelliJ may be more familiar.

4. Open a sample project (or create one) to check that it works.

If you use IntelliJ, make sure that the Android plugin is installed.

https://www.jetbrains.com/help/idea/getting-started-with-android-development.html

Page 7: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Setup

8

Android SDK tools are accessed through a drop-down menu in your IDE.

§ AVD Manager: manage Android Virtual Devices (AVDs) for testing.

§ SDK Manager: maintaining the SDK itself.

Page 8: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

SDK Manager

9

Page 9: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

AVD Manager

10

Page 10: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Sample Code

11

§ File -> Open (Project from Examples Directory)

§ Run, Select Deployment Target- Can launch AVD or push to connected device

Page 11: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Getting Started: Project Wizard

12

§ Company Domain- only important if you release your

app, can just use something like:cs349.uwaterloo.ca

§ API to target is the minimum Android version on target devices- Use API 15 for Phone and Tablet

(we won’t be doing anything restrictive)

§ SDK version is the version of the dev tools, libraries etc.- Android Studio defaults to 29

§ Activity: Whatever you start with, do NOT use fragments

Page 12: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Project Structure

13

§ Manifest (app/manifests/)- Application setting

§ Java (app/java/)- (*.java) source code

§ Resources (app/res/)- layout: (*.xml) UI layout and View

definitions- values: (*.xml) constants like strings,

colours, …- also bitmaps and SVG images

(mipmap*, drawable*, ….)

Page 13: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Manifest - Activities

14

§ Metadata about the app

§ App components, Intent filters

<applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme"><activity android:name=".MainActivity">

<intent-filter><action android:name="android.intent.action.MAIN" /><category

android:name="android.intent.category.LAUNCHER" /></intent-filter>

</activity></application>

Page 14: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Manifest – Permissions

15

§ Android must request permission to access sensitive user data

§ User is prompted once on application launch

§ Do not request more than you need (please!)

<manifest><uses-permission

android:name="android.permission.INTERNET" /><uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission

android:name="android.permission.SEND_SMS" /></manifest>

Page 15: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

App Resources

16

§ Each type of resource in located a specific subdirectory of your project's res/ directory

§ Access them using resource IDs that are generated in the project's R class

app/ manifest/ java/ res/

drawable/ graphic.png

layout/ activity_main.xml

mipmap/ icon.png

values/ strings.xml

Page 16: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Activities

18

§ The “standard” application component is an Activity

§ Typically represents a single screen of your application (and you may have multiple activities, one of which will be running at a time). - Not a view, since it can contains both model + view

§ One activity will be the Main entry point for your application (aka Main).

Page 17: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Activity Navigation

§ You can have multiple activities in your application (e.g. different screens), and switch between them as-needed.- Activities can create other activities (i.e. “back stack” of activities that

you can reach by using the back button)- Navigation forward/back through activities is typically triggered by

user actions

19

Page 18: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Activity Lifecycle

20

§ Activities have an explicit lifecycle, and have a state reflecting what they are doing (e.g. “started” or “stopped”)

§ Changing state fires a callback method that corresponds to that state (e.g. going from “stopped” to ”started” causes the onStart() method to fire).

RunningPaused

/ Stopped

https://developer.android.com/guide/components/activities/activity-lifecycle.html

Page 19: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Managing the Activity Lifecycle

21

Core callback functions:

§ onCreate()- being created or launching

§ onStart()- becomes visible to user

§ onResume()- prior to user interaction

§ onPause()- loses focus or background

§ onStop()- no longer visible to user

§ onDestroy()- being recycled and freed

Page 20: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Interrupted Workflow

22

§ Applications can stop at any time (i.e. user quits, OS kills it, user presses the Back button- the activity transitions through

the onPause(), onStop(), and onDestroy()callbacks.

- the activity is also removed from the stack.

§ onRestoreInstanceState() is automatically called by the system after onStart().

§ onSaveInstanceState() is automatically called by the system after onStop().

§ To preserve simple transient-state data, override these methods- Save data in onSaveInstanceState()- Restore data in onRestoreInstanceState()

Page 21: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Intents

23

§ An Intent is a messaging object you can use to request an action from another application component- Starting an activity- Starting a service- Delivering a broadcast

§ This allows an application to use other application services! e.g. Instagram app can request access to the Camera activity to take a picture.- Eliminates the need to have functionality embedded in an application.- Allows the OS to control access/permissions to services.

§ We use intents to pass data between activities.- Basically a data structure holding an abstract description of an action

https://developer.android.com/guide/components/intents-filters.html

Page 22: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Intents

24

§ Use startActivity() method to launch an activity with an intent.- Can call explicit named activity (e.g. mySettingsActivity) or an

implicit activity based on its capabilities (e.g. some camera activity)

Page 23: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Android UI DevelopmentView hierarchies

Using different layouts

Using UI widgets

MVC

26

Page 24: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Building User Interfaces

27

android.view.ViewGroup

§ Abstract container class that includes the layout

§ Subclasses: LinearLayout, RelativeLayout, GridLayout, …

android.view.View

§ Base widget class (i.e. drawing and event handling)

§ Subclasses: android.widget.Buttonandroid.widget.ImageViewandroid.widget.ProgressBarAndroid.widget.TextView...

Page 25: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

User Interface Classes

28

§ UI is built using a hierarchy of View and ViewGroup- A ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects

- A View usually draws something the user can see and interact with

https://developer.android.com/guide/topics/ui/declaring-layout.html

Page 26: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Common Layouts

29

§ Each subclass of the ViewGroup class provides a unique way to display the views you nest within it

Grid ViewDisplays items in a two-dimensional,

scrollable grid

Linear LayoutA layout that organizes

its children into a single horizontal or

vertical row

Relative LayoutEnables us to specify the location of child objects relative to

each other or to the parent.

Page 27: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Specialized Layouts

30

RecyclerView

§ Display very long lists of items (and have the OS load/unload the items as you scroll).

§ https://developer.android.com/guide/topics/ui/layout/recyclerview

CardView

§ Customized cards (e.g. panels) that needs to be repeated over and over again.

§ e.g. blog posts each with a card

https://developer.android.com/guide/topics/ui/layout/cardview

Page 28: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

UI Definition and Layout

31

§ Layout can be handled in one of two ways:- Programmatic: write code. You write code to instantiate ViewGroups,

Views and bind them together (like in Java Swing).- Declarative: use XML to describe your layout. In XML describe the screen

elements (view groups and views) along with properties, and then tell your application to dynamically load it.

§ Using XML is the preferred way- Android Studio & IntelliJ both include a GUI builder to make this easier!

Page 29: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Layout: WYSIWYG Version

33

Page 30: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Layout: XML Version

34

Page 31: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Layout Example

35

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent">

<EditTextandroid:id="@+id/editTextName”android:layout_alignParentTop="true”android:layout_marginTop="30dp"android:ems="12"android:text="@string/name”… />

<Buttonandroid:id="@+id/btnConfirm"android:layout_below="@id/editTextName"android:layout_marginTop="40dp"android:text="@string/confirm"… />

</RelativeLayout>

Page 32: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Layout

36

§ When you compile your app, each XML layout file is compiled into a View resource

§ calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name.

§ app/java/MainActivity.java

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);

}

Page 33: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Linear Layout

37

§ LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.

§ You can specify the layout direction with the android:orientationattribute.

§ All children of a LinearLayout are stacked one after the other - a vertical list will only have one child per row, no matter how wide is it- a horizontal list will only be one row high

https://developer.android.com/guide/topics/ui/layout/linear.html

Page 34: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Key Attributes

38

§ Orientation- Should the layout be a column or a row? Use "horizontal" for a

row, "vertical" for a column.

§ Fill model - MATCH_PARENT: the view wants to be as big as its parent- WRAP_CONTENT: the view wants to be just large enough to fit its

own internal content

§ Weight- android:layout_weight attribute assigns an "importance"

value to a view in terms of how much space it should occupy on the screen.

Page 35: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Attributes

39

§ Gravity - Specifies how an object should position its content, on both the X

and Y axes (top, bottom, center,…)

§ Padding/margin- Setting padding/margin

Page 36: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

LinearLayout

40

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingLeft="16dp"android:paddingRight="16dp"android:orientation="vertical" ><EditText

…/><EditText

…/>

<Button…

/></LinearLayout>

Page 37: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

LinearLayout

41

<LinearLayout …><EditText

android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/to" />

<EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/subject" />

<EditTextandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:gravity="top"android:hint="@string/message" />

<Buttonandroid:layout_width="100dp"android:layout_height="wrap_content"android:layout_gravity="right"android:text="@string/send" />

</LinearLayout>

Fill

Page 38: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Relative Layout

42

§ RelativeLayout is a view group that displays child views in relative positions.

§ The position of each view can be specified as - relative to sibling elements (such as to the left-of or below another view) - in positions relative to the parent’s area (such as aligned to the bottom,

left or center).

https://developer.android.com/guide/topics/ui/layout/relative

Page 39: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

View Positioning

43

§ RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID).

§ By default, all child views are drawn at the top-left of the layout

§ Example of some layout properties : - android:layout_alignParentTop- android:layout_centerVertical- android:layout_below- android:layout_toRightOf- More: RelativeLayout.LayoutParams

https://developer.android.com/guide/topics/ui/layout/relative

Page 40: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

View Positioning in Relative Layout

44

android:layout_aboveandroid:layout_below

android:layout_toLeftOfandroid:layout_toRightOf

android:layout_alignBottomandroid:layout_alignTop

android:layout_alignLeftandroid:layout_alignRight

Widget 1

Widget 2

Widget 2

Widget 1

Widget 1Widget 2 Widget 2Widget 1

Widget 1Widget 2

Widget 1Widget 2

Widget 1

Widget 2

Widget 1

Widget 2

Page 41: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Relative layout alignment parameters

45

android:layout_alignParentTopandroid:layout_alignParentLeftandroid:layout_alignParentRight

android:layout_centerInParentandroid:layout_centerVerticalandroid:layout_centerHorizontal

android:layout_alignParentBottom

Page 42: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

46

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingLeft="16dp"android:paddingRight="16dp" ><EditText

…/><Spinner

…/>

<Spinner…

/><Button

…/>

</RelativeLayout>

Relative Layout

Page 43: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

47

<RelativeLayout …<EditText

android:id="@+id/name"android:layout_width="match_parent"android:layout_height="wrap_content” />

<Spinnerandroid:id="@+id/times"android:layout_width="96dp"android:layout_height="wrap_content"android:layout_below="@id/name"android:layout_alignParentRight="true" />

<Spinnerandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_below="@id/name"android:layout_toLeftOf="@id/times”android:layout_alignParentLeft="true” />

<Buttonandroid:layout_width="96dp"android:layout_height="wrap_content"android:layout_below="@id/times"android:layout_alignParentRight="true"android:text="@string/done" />

</RelativeLayout>

Page 44: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Layout test

49

§ Check the layout with multiple screen sizes

Page 45: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Code Demo: WidgetDemo

50

§ Notes- TextView- EditText- RadioButton- CheckBox- Spinners- Relative Layout- Linear Layout- Nested Layout

Page 46: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Nested Layout

51

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextView

android:id="@+id/name_title"android:text=“@string/name">……

</EditText>……

<LinearLayoutandroid:layout_below="@+id/session">………<CheckBox

android:id="@+id/checkbox_morning"android:text="@string/morning”…… />

<CheckBox…… />

</LinearLayout></RelativeLayout>

Views

Views

Page 47: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

View (Widget)

52

Properties:

§ Background color, text, font, alignment, size, padding, margin, etc

Event Listeners and Handlers:

§ respond to various events such as: click, long-click, focus change, etc.

Set focus:

§ Set focus on a specific view requestFocus() or use XML tag <requestFocus />

Visibility:

§ You can hide or show views using setVisibility(…).

Page 48: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Views: TextViews

53

<TextViewandroid:id="@+id/txtHello"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!" />

TextView helloTextView = findViewById(R.id.txtHello);helloTextView.setText("CS349 W19");

Page 49: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Views: EditText

54

<EditTextandroid:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content”android:inputType="textPersonName" android:text=”@string/name” ><requestFocus/>

<EditText/>

EditText nameView = findViewById(R.id.name);String name = nameView.getText().toString();

Page 50: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Views: Buttons

55

<Buttonandroid:id="@+id/btnAlarm"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/alarm" />

https://developer.android.com/guide/topics/ui/controls/button.html

Button button = (Button) findViewById(R.id.btnAlarm);. . .

Page 51: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Responding to Events

56

<Buttonandroid:id="@+id/btnAlarm"……android:onClick="sendMessage"/>

/** Called in activity when the user touches the button */public void sendMessage(View view) {

// Do something in response to button click}

Button button = (Button) findViewById(R.id.btnAlarm);button.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {// Do something in response to button click

}});

§ Option 1: Listeners

§ Option 2: Registered in Layout file

Page 52: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Radio Buttons

57

<RadioGroupandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><RadioButton

android:id="@+id/radio_yes"android:layout_width="wrap_content"android:layout_height="wrap_content"android:weight=”1"android:onClick="onRadioButtonClicked"android:text="@string/yes" />

<RadioButtonandroid:id="@+id/radio_no"android:layout_width="wrap_content"android:layout_height="wrap_content"android:weight=”1"android:onClick="onRadioButtonClicked"android:text="@string/no" />

</RadioGroup>

Page 53: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Radio Buttons

58

public void onRadioButtonClicked(View view) {// Is this button checked?boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clickedswitch (view.getId()) {

case R.id.radio_yes:if (checked)

// code for yesbreak;

case R.id.radio_maybe:if (checked)

// code for may bebreak;

case R.id.radio_no:if (checked)

// code for nobreak;

}}

https://developer.android.com/guide/topics/ui/controls/radiobutton

Page 54: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Checkboxes

59

<CheckBoxandroid:id="@+id/checkbox_morning"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="onCheckboxClicked"android:text="@string/morning" />

<CheckBoxandroid:id="@+id/checkbox_afternoon"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="onCheckboxClicked"android:text="@string/afternoon" />

https://developer.android.com/guide/topics/ui/controls/checkbox.html

Page 55: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Checkboxes

60https://developer.android.com/guide/topics/ui/controls/checkbox.html

public void onCheckboxClicked(View view) {// Is the view now checked?boolean checked = ((CheckBox) view).isChecked();

// Check which checkbox was clickedswitch (view.getId()) {

case R.id.checkbox_morning:if (checked)// Add morning session

else// Remove morning sessionbreak;

case R.id.checkbox_afternoon:if (checked)// Add afternoon session

else// Remove afternoon sessionbreak;

}}

Page 56: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

ImageView

61

§ Display images

§ Save image resources to drawable folder- app/src/main/res/drawable/

<ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content”android:src="@drawable/lollipop" />

Page 57: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Multiple Views ApplicationUsing intents to launch activities

MVC in Android

ViewModel

65

Page 58: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Activity Lifecycle

66

§ Usually, one view per activity

§ Only one activity is running at any given time

§ We often want to let users navigate between different views.

§ How can we share data between views? Intents

RunningRunning

Paused

Page 59: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Start Another Activity: Pass Data

67

int version = 0;switch (radio_id){

case R.id.radioButton1:version = 6;break;

Intent intent = new Intent(this, VersionActivity.class);intent.putExtra("version", version); // data to passstartActivity(intent);

Page 60: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Start Another Activity: Receive Data

68

// Get the Intent that started this activity //and extract the value in intIntent intent = getIntent();int v = intent.getIntExtra("version",0);

// Set the string match to the valueTextView label = findViewById(R.id.version_txt);switch(v){

case 6:label.setText(R.string.v6);

Page 61: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Return “Home” to Previous Activity

69

§ In Manifest file, specify “parentActivity”

<applicationandroid:allowBackup="true”

…>

<activity android:name=".MainActivity">…

</activity>

<activity android:name=".VersionActivity"android:parentActivityName=".MainActivity”>

</activity></application>

Page 62: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

MVC in Android

70

With MVC, there is a data model that ensures consistent state across views.

Android makes MVC difficult, because

§ Activities cannot easily share data (since they exist independently)

§ An activity that creates a model may be later paused or destroyed.

How do we share our data across activities? Options:

1. Save and restore data within each activity.

2. Create a static model that is shared between activities.

3. Use Google’s ViewModel, a persistent Model class that survives activity changes.

Page 63: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

MVC Structure Option 1: Save and Restore Data

71

view2.xmlView2

MainActivity

Model

view1.xmlView1

ViewGroup

ViewGroup

Activity Other ClassUI xml

Page 64: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Code Demo: MVC1

72

§ Views as Android ViewGroups- similar to desktop MVC we discussed earlier

§ Notes:- Model essentially identical to desktop Java- “Inflating” view layouts into main view- onPostCreate() when inflating view layouts- Save and restore model

Page 65: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Recreating an Activity

73

protected void onSaveInstanceState(Bundle outState) {outState.putInt("Counter", model.getCounterValue());...

}

protected void onRestoreInstanceState(Bundle savedInstanceState) {model.setCounterValue(savedInstanceState.getInt("Counter"));...

}

Use built-in methods to save and restore model state.

Page 66: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Application

MVC Structure Option 2: Shared Static Model

74

View1Activity

Model

view1.xmlcontentView

Activity Other ClassUI xml

View2Activity

view2.xmlcontentView

intents

Page 67: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

Code Demo: MVC2

75

§ Views as Activities, global static model

§ Notes:- Application class- onDestroy(), deleteObserver()

- Create options menu- Intents to start activity- finish()

- no need to persist model!

Page 68: Android Introduction - University of Waterloo · Architecture 5 §Applications are built in Java (or Kotlin, or C++)-Android compiler generates an Android Package (.apkfile), which

MVC Structure Option 3: ViewModel

76

Google provides a ViewModel helper class

§ Use to asynchronously fetch data.

§ Persists across Activities.

https://developer.android.com/topic/libraries/architecture/viewmodel#java