23442 ECE 09402 7 Introduction to Android Mobile Programming 23442 ECE 09504 7 Special Topics: Android Mobile Programming

Similar documents
ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

2. Click the download button for your operating system (Windows, Mac, or Linux).

Now that we have the Android SDK, Eclipse and Phones all ready to go we can jump into actual Android development.

Getting Started with Android

Getting Started: Creating a Simple App

Android Java Live and In Action

Admin. Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources. Recap: TinyOS. Recap: J2ME Framework

Android Development. Marc Mc Loughlin

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

Tutorial #1. Android Application Development Advanced Hello World App

INTRODUCTION TO ANDROID CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 11 02/15/2011

Android Mobile App Building Tutorial

OpenCV on Android Platforms

Android Application Development: Hands- On. Dr. Jogesh K. Muppala

Android Basics. Xin Yang

How to develop your own app

Lab 0 (Setting up your Development Environment) Week 1

Lecture 1 Introduction to Android

Android Programming Basics

Developing NFC Applications on the Android Platform. The Definitive Resource

Developing Android Apps: Part 1

Android Environment SDK

directory to "d:\myproject\android". Hereafter, I shall denote the android installed directory as

CS 528 Mobile and Ubiquitous Computing Lecture 2: Android Introduction and Setup. Emmanuel Agu

Chapter 2 Getting Started

Mobile Application Development 2014

IOIO for Android Beginners Guide Introduction

Android Development. 吳 俊 興 國 立 高 雄 大 學 資 訊 工 程 學 系

Mobile Application Development

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

Android Environment SDK

Hypercosm. Studio.

Tutorial on Basic Android Setup

Basic Android Setup Windows Version

Creating a 2D Game Engine for Android OS. Introduction

Lab 1 (Reading Sensors & The Android API) Week 3

Introduction to Android SDK Jordi Linares

@ME (About) Marcelo Cyreno. Skype: marcelocyreno Linkedin: marcelocyreno Mail:

Android Tutorial. Larry Walters OOSE Fall 2011

How to Install Applications (APK Files) on Your Android Phone

4. The Android System

Source Code Translation

Running a Program on an AVD

Android Concepts and Programming TUTORIAL 1

Login with Amazon Getting Started Guide for Android. Version 2.0

TUTORIAL. BUILDING A SIMPLE MAPPING APPLICATION

MEAP Edition Manning Early Access Program Hello! ios Development version 14

Building Your First App

Android Programming and Security

Mobile Application Development Android

MMI 2: Mobile Human- Computer Interaction Android

Advantages. manage port forwarding, set breakpoints, and view thread and process information directly

Workshop on Android and Applications Development

Introduction to Android Programming (CS5248 Fall 2015)

NETGEAR genie Apps. User Manual. 350 East Plumeria Drive San Jose, CA USA. August v1.0

Table of Contents. Adding Build Targets to the SDK 8 The Android Developer Tools (ADT) Plug-in for Eclipse 9

Learning Material Design

Mocean Android SDK Developer Guide

The "Eclipse Classic" version is recommended. Otherwise, a Java or RCP version of Eclipse is recommended.

Android Programming. Høgskolen i Telemark Telemark University College. Cuong Nguyen,

RingCentral from AT&T Desktop App for Windows & Mac. User Guide

With a single download, the ADT Bundle includes everything you need to begin developing apps:

How to Create an Android Application using Eclipse on Windows 7

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Getting Started. Version 3.1 Last updated 2014/3/10. Orbweb ME: Getting Started

How To Use Titanium Studio

Introduction to NaviGenie SDK Client API for Android

Hello World. by Elliot Khazon

SMART Board User Guide for PC

Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department. Mobile Computing ECOM Eng. Wafaa Audah.

Homework 9 Android App for Weather Forecast

Android Application Development - Exam Sample

UNIVERSITY AUTHORISED EDUCATION PARTNER (WDP)

Generate Android App

Using Microsoft Visual Studio API Reference

Windows 8 Features (

How To Develop Android On Your Computer Or Tablet Or Phone

Syllabus for CS 134 Java Programming

Android Setup Phase 2

Frameworks & Android. Programmeertechnieken, Tim Cocx

Android Developer Fundamental 1

Android Application Development

Appium mobile test automation

Backend as a Service

Presenting Android Development in the CS Curriculum

ios App for Mobile Website! Documentation!

Setting up Sudoku example on Android Studio

Arduino & Android. A How to on interfacing these two devices. Bryant Tram

ID TECH UniMag Android SDK User Manual

Gauge Drawing Tool Slider Drawing Tool Toggle Button Drawing Tool One-Way List Drawing Tool... 8

SDK Quick Start Guide

Mobile Game and App Development the Easy Way

Android App Development Lloyd Hasson 2015 CONTENTS. Web-Based Method: Codenvy. Sponsored by. Android App. Development

Android Programming: Installation, Setup, and Getting Started

Transcription:

23442 ECE 09402 7 Introduction to Android Mobile Programming 23442 ECE 09504 7 Special Topics: Android Mobile Programming Mondays 5:00 PM to 7:45 PM SJTP, Room 137 Portions From Android Programming The Big Nerd Ranch Guide Android How to Program 2 nd Edition Udacity Android Studio Application Development Learning Android Intents Course Summary Android Version 4.x - 5.0 course You need a laptop in class and you can use PC, Mac, Linux but everything I do will be on a PC Meant to get you over the beginner hump for Android development Android is HUGE, we will cover a little of everything Course has a lecture and pseudo-lab format Always bring a computer to work in class 1

Syllabus Course Website: http://users.rowan.edu/~lecakes Contains: Course Overview Lectures Homework Due Dates Course Material (Slides, HW, Syllabus) Syllabus - Grading Grading Percentages % Homework 30 Attendance & Professionalism 10 Midterm 30 Final Project 30 SUM 100 Letter Percent F 0 D- 60 D 63 D+ 67 C- 70 C 73 C+ 77 B- 80 B 83 B+ 87 A- 90 A 95 2

Course Introduction - Midterm The course will have a midterm after spring break It will be based on theory The midterm is typically 5 essay questions with multiple parts (for a total of around 10-14 parts) Undergrads gets to omit a certain number of questions, Graduates omit fewer if any Closed notes / closed text / no cheat sheets About Android Why Learn? Android is a linux-based OS for touch screens and mobile tablets OS was founded in October 2003, at the time mobiles were using Symbian and Windows Mobile Google purchased Android Inc. in 2005, causing many rumors in the industry In Nov 2007 the Open Handset Alliance was created to develop an open standard for mobile devices Android was the first product, backed by a consortium of 65 companies 3

About Android Why Learn? The first generation of phones (HTC Dream) were released in October 2008 The nexus series was launched in 2010 By October 2013, Android had 81.3% of the market By Q1 2013, Android had 56.5% of the tablet market As of April 2013, there were more than 1.5 million Android devices activated daily About Android - Versions https://developer.android.com/about/dashboards/index.html 4

About Android Features Android is a Linux-based operating system and is open source It is easily modifiable by vendors Uses the Java language Supports single, multitouch and gestures Touch tap screen once Double Touch tag screen twice Long Press touch and hold position Swipe touch and move finger and release Drag touch and drag across screen Pinch Zoom Pinch fingers on screen apart / together About Android Features Android versions before 3.0 are for mobile devices Android versions between 3 and 4 were for tablets Android was unified in version 4 across mobile devices, tablets, TVs, etc We will be using Android 4.X features because it is: Relatively current Widespread Reduces B.S. code for supporting old devices 5

Setting Up Android Studio Originally, this course was going to use Eclipse However, between October and now, Android Studio has become the supported IDE Google Android SDK and navigate and download Android Studio Install the application Install Java 7 SDK (Google it) Run the application Setting Up Android Studio When you first start Android Studio you will get the following window (minus the recent projects section) Click on start a new Android Studio project 6

Setting Up Android Studio Your app name is what will be listed in the Android Store! Your company name is used to differentiate you from everyone else! In this class, use the convention: first&lastname.com Store your files in a convenient location Reverse DNS convention Keeps packages unique Distinguishes apps from one another on Google Play Store Lowercase! Setting Up Android Studio Android will ask you the minimum SDK you want to support Choose API 15 (supporting 87.9% of devices) 7

Setting Up Android Studio While Android Studio features emulators, it can not emulate all functionality I highly recommend picking up an Android device to test on Devices can be VERY cheap, and range from tablets to cellphones Just make sure it has at least Android 4.0+ We will not be discussing Android Wear, Android TV, or Google Glass Java What is Java? A language and platform originally from Sun Microsystems Java s syntax is like C & C++ (C#) Comment styles are the same Many reserved keywords are the same Most basic types are the same (char, double, int, etc ) Arithmetic operators are similar ( +, -, *, %, etc ) Uses braces {}, (), [] Some differences: Java has commenting called Javadoc New reserved keywords: extends, implements Meant to be safer than C/C++ No overloading operators No pointers, includes garbage collections 8

Java Java is also a platform consisting of a virtual machine and an execution environment Virtual machine software based processor (JVM) The environment contains libraries for interacting with the underlying operating system (native platform) The Java compiler translates source code into object code that can be executed by the JVM (bytecode) stored in files with a *.class extension The JVM then interpreter converts the bytecode into native instructions OOP What is OOP? Object-Oriented Programs utilize Objects Objects are representations comprised of both attributes and behaviors Objects perform operations when receiving a request/message from a client Requests are the ONLY* way to get an object to execute an operation or change the object s internal data This means an object s internal state is encapsulated (invisible from outside the object) 9

OOP Why use Object Oriented Programming? Encapsulate a variety of attributes (variables) and methods (functions) into a single package Reuse existing functionality or override it! Attributes have names, helping humans remember what they mean Establish best practices and enforce implementations Restrictions can be imposed to stop inappropriate use Allows for programming that emulates reality OOP What Is Difficult About OOP? Decomposing a system into objects During decomposition we will think about: Encapsulation Granularity Dependency Flexibility Performance Evolution Reusability and much more While there are design patterns to help us, many situations call for different strategies (and that is where it gets complex!) 10

OOP A class is a data type / object type A class is a template (blueprint) used to create objects Classes are abstract models for ideas or concepts Describes how to package both data and procedures this.color this.maxspeed this.efficiency this.start(self) this.steer(self, angle) OOP An instance is an object generated from a class A class is just a definition of the object To use a class, you need to create an instance! A class = blueprint An instance = actual car 11

OOP Instance attributes are UNIQUE to the instance Each instance of a car has separate values (DEFAULT) this.color = None this.maxspeed = 0 this.efficiency = 0 this.color = Blue this.maxspeed = 65 this.efficiency = 48 this.color = Red this.maxspeed = 150 this.efficiency = 12 this.color = Black this.maxspeed = 80 this.efficiency = 24 this.color = Green this.maxspeed = 200 this.efficiency = 8 OOP We can create class-wide (static) variables shared across the class and all instances Example: number of cars sold Mazda.carsSold = 4 self.color = None self.maxspeed = 0 self.efficiency = 0 Mazda.carsSold = 0 self.color = Blue self.maxspeed = 65 self.efficiency = 48 Mazda.carsSold = 2 self.color = Red self.maxspeed = 150 self.efficiency = 12 Mazda.carsSold = 1 self.color = Black self.maxspeed = 80 self.efficiency = 24 Mazda.carsSold = 3 self.color = Green self.maxspeed = 200 self.efficiency = 8 12

OOP Class can also have methods (behaviors / functions) that perform tasks. Can be instance or class methods. Mazda.carsSold = 4 self.color = None self.maxspeed = 0 self.efficiency = 0 public void drive() Mazda.carsSold = 1 self.color = Blue self.maxspeed = 65 self.efficiency = 48 Mazda.carsSold = 3 self.color = Red self.maxspeed = 150 self.efficiency = 12 Mazda.carsSold = 2 self.color = Black self.maxspeed = 80 self.efficiency = 24 Mazda.carsSold = 4 self.color = Green self.maxspeed = 200 self.efficiency = 8 OOP - Inheritance Inheritance allows for code reuse A class can be built off an existing class to add additional functionality without rewritting all the previous methods and attributes A child class can also override previous functionality (@Override for compile time checking) The following slides are an example for using inheritance: 13

OOP - Inheritance Example Lets create a class to represent different NPC or player characters in a game: Lets start with the most general thing we can think of: An entity - something that exists in 3D space Entity will be a base class for classes needing a physical location A entity has attributes (member variables): protected String name protected float position[3] Entity mname mposition OOP - Inheritance Example Entity is very simple If we want a new, more complex type of Entity we can reuse Entity When designing classes, we try to group common attributes together into base classes Entity name position This allows us to build upon previously developed code We do this through inheritance Something that is an Entity but more 14

OOP - Inheritance Example A Human is an Entity It contains everything that an Entity is + more Human adds: mhitpoints mpower mtoughness mitem getpower( self ) gettoughness( self ) swapitem( self, item ) isalive( self ) Base Class Super Class Parent Class Entity Human Derived Class Sub Class Child Class Human Entity mname mposition mhitpoints mpower mtoughness mitem getpower() gettoughness() swapitem() isalive() Creating Your First App Creates a skeleton framework Blank blank activity with an action bar with title and options menu Fullscreen hides the system user interface, action bar shows up on touch Login looks like a login page Master/Detail screen in two sections for menu and details Settings preferences with a list of settings 15

Creating Your First App Activity Name: The name of your activity according Layout Name: Notice the convention of activity (fragment) _ name Title: The name of the title set as a string Menu Resource Name: The name of the menu for the activity bar Creating Your First App What is an activity? An activity is an instance of the class Activity, part of the Android SDK Activities manage user interaction with a screen of information Activities you create will be subclasses of the class Activity You spawn different activities to show different screens 16

Creating Your First App What is a layout? Defines user interface objects Definitions are written in XML Each definition creates an object on screen, such as a button or text An activity inflates and manages the layout defined in the XML file. Creating Your First App What is XML? EXtensible Markup language (similar to HTML) Defines rules for describing data Human-readable and machine-readable Uses <> and </> to denote tags Free to define your own tags: <ILoveAndroid> </ILoveAndroid> 17

Creating Your First App Android uses XML to make user interfaces layouts, menus, sub menus and much more! We can define strings, colors, drawables etc You ll find these under your res folder under other folders for: Layout how widgets are arranged Menu quick access for options, pop-ups Values styles, strings, dimensions Manifest Android app info for the structure Creating Your First App 18

Creating Your First App Creating Your First App 19

Creating Your First App Creating Your First App 20

Creating Your First App By default you will see the Android graphical layout tool and the structure of your blank activity Use the tabs on the bottom to see the design or text (xml) You will also see the project itself, which can be organized in 3 ways Creating Your First App Running your App You will run on the emulator or on the device Emulators require downloading an image Devices require installing USB drivers on Windows 21

Creating Your First App - Emulator ADV Manager virtual devices for emulation SDK Manager different android versions and their required SDKs that you can download Android Device Monitor monitors the devices you have connected for log information Creating Your First App SDK Manager By default, Android Studio will have downloaded and installed the latest SDK for us If you are looking to target a specific version, you may want to download that SDK version by check boxes and hitting install You ll want to install the Intel Atom Image as well as the Intel x86 Emulator Accelerator in the Extras folder! & Support Library! 22

Creating Your First App - Emulator If your running with an Intel processor, you ll want to install the Intel x86 Emulator Accelerator (the SDK only downloads it) If it is not automatically installed by Android Studio, go into the extras folder under studio In my case this is at under extras, intel C:\Users\George\AppData\Local\Android\sdk This will SIGNIFICANTLY increase the speed of the emulator, so if you have an intel processor, do it! Creating Your First App - Emulator 23

Creating Your First App - Emulator I suggest picking an emulator for a phone and a tablet such as a Nexus 5 and Nexus 9 You can clone a device as a base and create your own emulator to suite unlisted devices Creating Your First App - Emulator Choose the Google API version and the x86 version so that we can benefit from the intel emulator speedup! 24

Creating Your First App - Emulator Last chance to make a change Use Host GPU if possible Snapshot means it retains data Creating Your First App - Emulator Press the green run button and you ll get a choose device dialog Choose launch emulator and choose the virtual device Use same device if you want to auto launch I recommend NOT closing the emulator! 25

Creating Your First App - Emulator If the app doesn t launch, just press run again Will give you the choice of devices, choose your existing emulator Congrats, you just ran your first app Creating Your First App - Device Running your App on a Device 1. You need an android device at the min SDK or higher 2. You need a USB cable of appropriate type 3. You need to unlock developer mode on the device 4. You might want to setup Paths 5. You may need to install USB drivers 26

Creating Your First App - Device To unlock developer options, go to settings->about Phone and press build number 7 times May vary on your make and model android device Creating Your First App - Device Go to SDK folder in: C:\Users\Name\AppData\Local\Android\sdk Open you environmental variables folder To you Path variable add: tools path platform-tools path 27

Creating Your First App - Device Under Applications, check Unknown Sources Enable USB debugging Connect to your computer (USB) Launch your command prompt Start->Run cmd or the terminal in studio Type the following: adb devices You should see the device now! Creating Your First App - Device 28

Creating Your First App - Device If you do not get your device recognized, we need to install the USB drivers Go to : https://developer.android.com/tools/extras/oemusb.html#installingdriver Follow instructions: Windows 7 To install the Android USB driver on Windows 7 for the first time: 1. Connect your Android-powered device to your computer's USB port. 2. Right-click on Computer from your desktop or Windows Explorer, and select Manage. 3. Select Devices in the left pane. 4. Locate and expand Other device in the right pane. 5. Right-click the device name (such as Nexus S) and select Update Driver Software. This will launch the Hardware Update Wizard. 6. Select Browse my computer for driver software and click Next. 7. Click Browse and locate the USB driver folder. (The Google USB Driver is located in<sdk>\extras\google\usb_driver\.) 8. Click Next to install the driver. Pushing Buttons Lets edit our app to make it more useful Goals: Look at the layout in XML Add buttons and text to the layout Format the location of objects on the screen Edit the java code to respond to button presses Show a temporary message to the user (toast) 29

Pushing Buttons Anything that isn t code is regarded as a resource Resources are stored in the res folder Android provides you with several default folders, but there are more! Open up the layout folder and double click on activity_profiles.xml Pushing Buttons Drawables usually contain images Layouts contain XML files that describe GUIs Values contain arrays, colors, dimensions, styles in XML files Here we have two different views: Android and Packages which show the different folders available 30

Pushing Buttons Switch to the text tab for the layout: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context=".profilesactivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content android:layout_height="wrap_content" /> </RelativeLayout> Pushing Buttons Widgets the building blocks used to create an interface Buttons, text input controls, check boxes are all widgets All widgets are children of the View class The default layout contained two items, a layout element that defines how the page is structured and a generic text view for displaying text: 31

Pushing Buttons XML Elements: <RelativeLayout> <TextView> XML Element Attributes: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> Pushing Buttons For fun as our first app, lets create a layout that mimics nearly every dating application on the market First, we need to plan out our user interface A great strategy is to first develop a prototype We are going to use the open-source application Pencil Project http://pencil.evolus.vn/ 32

Pushing Buttons Planning In android we need to create a layout to hold these elements: We need: Picture A layout that arranges elements vertically stacked on one another Within this stack will be a photo, a text object and two buttons side by side The side by side buttons should have something to lay them out as well No Text Yes Pushing Buttons Planning Start with the XML layout We need: A vertical linear layout holding: A placeholder for out images A text view for our message A horizontal linear layout holding: A button for no A button for yes 33

Pushing Buttons XML Layout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin android:orientation="vertical" tools:context=".profilesactivity"> <TextView android:layout_width = "wrap_content" android:layout_height="wrap_content" android:text="@string/duck_face_text android:padding="24dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/question_text /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/yes_text"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/no_text"/> </LinearLayout> </LinearLayout> Required xml namespace on the root element Fills the parents space Is as large as the content held within Padding around text A reference to a string resource stored in XML Pushing Buttons XML Layout Your going to have some errors and this is because we made reference to some objects that don t exist String literals can be manually defined or entered in an XML document Why do this? Because it helps with a topic called localization we ll hit on in later weeks 34

Pushing Buttons XML Layout android:layout_width & android:layout_height match_parent view as big as parent wrap_content view as big as contents Deprecated: fill_parent equivalent to match_parent (confusing) For the root element (LinearLayout) make it match_parent to fill the entire view that android provides for your layout to exist within Pushing Buttons XML Layout android:padding= 24dp Attribute puts space around the contents when determining size dp = density-independent pixels, which we ll talk more about when we discuss images 35

Pushing Buttons XML Layout android:orientation Within LinearLayout, determines if children are placed vertically or horizontally The order of the children defines where they appear in the layout Top to bottom, left to right Unless the language is right-to-left such as with Arabic or Hebrew Pushing Buttons XML Layout android:text For a TextView or Button, displays text within You can specify a string literal: android:text= Ermahgerd a string! It is better to reference a string resource Lets learn how to add string resources now-> 36

Pushing Buttons XML Layout Under res->values->strings.xml Go to the xml tab You don t have to name the file strings.xml, this is the default You can place any XML files of strings in res/values so long as you have the <resources> tag Pushing Buttons XML Layout Gravity for a layout is how items are aligned internally In this case, object are centered both horizontally and vertically Play around with the different gravity settings to understand how items are placed 37

Pushing Buttons Activity In Android project view under java you will find the package name followed by the classes within Double-click on our class Activity to open the code view Pushing Buttons Activity package com.georgelecakes.profilegenerator; import android.support.v7.app.actionbaractivity; import android.os.bundle; import android.view.menu; import android.view.menuitem; public class ProfilesActivity extends ActionBarActivity { //Next slide shows class code } package a namespace for organizing code, like a folder import used for importing entire packages or classes public defines a publically accessible class in the package class keyword to define creating a class extends used to inherit from a parent class ActionBarActivity a subclass of Activity, change this to Activity! 38

Pushing Buttons Activity public class ProfilesActivity extends Activity{ @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_profiles); } @Override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.menu_profiles, menu); return true; } @Override public boolean onoptionsitemselected(menuitem item) { int id = item.getitemid(); if (id == R.id.action_settings) { return true; } return super.onoptionsitemselected(item); } Pushing Buttons Activity public class ProfilesActivity extends Activity{ @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_profiles); } @Override optional, makes sure the superclass has the method protected accessible to child classes, hidden from others void no object returned from the method oncreate called during instantiation, before visible Bundle Android object holding previous instance information super used to call the superclass method (required!) setcontentview convenience method to inflate an XML layout R.layout. a static integer generated by the IDE for us 39

Pushing Buttons Activity @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_blank); } We need to call the super class method oncreate IMMEDIATELY in order to properly setup the activity We pass the savedinstancestate, which provides information saved from the last time the instance was run setcontentview inflates a layout using its Id, in the R file Inflate instantiates each widget in the XML using the defined attributes Pushing Buttons R File What is an R file? Holds resource Ids for your XML objects Allows the Java side to work with the XML side through integer resources A resource is ANYTHING that is not code (images, audio, XML files) and live with the res directory To access these resources in code, we need to use resource IDs This file is automatically generated, don t bother changing it! 40

Pushing Buttons R File String resource files: public static final class string { public static final int duck_face_text=0x7f0a0011; public static final int hello_world=0x7f0a000e; public static final int no_button=0x7f0a0013; public static final int question_text=0x7f0a0010; public static final int yes_button=0x7f0a0012; } We access these integer resources in our activities: settext(r.string.question_text); Pushing Buttons R File To force a resource ID for a widget, include the id attribute using the following format: <Button android:id= @+id/yes_button /> <Button android:id= @+id/no_button /> The + sign indicated that we want to create an Id if none exists Go check your R file and find the new layout integers (Yes you can add Ids without the + notation, we ll get to it) 41

Pushing Buttons R File public static final class id { public static final int action_bar=0x7f05001c; public static final int action_bar_activity_content=0x7f050015; public static final int action_bar_container=0x7f05001b; public static final int action_bar_overlay_layout=0x7f05001f; public static final int action_bar_root=0x7f05001a; public static final int action_bar_subtitle=0x7f050023; public static final int action_bar_title=0x7f050022; public static final int action_context_bar=0x7f05001d; public static final int action_menu_divider=0x7f050016; public static final int action_menu_presenter=0x7f050017; public static final int action_mode_close_button=0x7f050024; public static final int action_settings=0x7f05003e; public static final int activity_chooser_view_content=0x7f050025; public static final int always=0x7f05000b; public static final int beginning=0x7f050011; public static final int button_no=0x7f05003d; public static final int button_yes=0x7f05003c; Pushing Buttons Wiring Widgets With Ids to the widgets, we can access them in the activity class Finding the instances of the widgets can be performance limiting, it is best to find them once in the oncreate method and store references: private Button myesbutton; private Button mnobutton; m prefix means member variable Use camel-case with variable names starting lower-case 42

Pushing Buttons Wiring Widgets private Button myesbutton; private Button mnobutton; @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_blank); myesbutton = (Button) findviewbyid(r.id.button_yes); mnobutton = (Button) findviewbyid(r.id.button_no); } Create two private variables to hold reference to the buttons findviewbyid() returns a view object if we specify a widget ID findviewbyid() returns a view, thereforewe need to cast to the type Button (which inherits from View) Type R. and it will auto fill possible values Pushing Buttons Listeners We need to listen for an event to occur That event is the press of the yes or no button We achieve this by creating a class instance that inherits from the OnClickListener Class However, we are lazy. We don t want to go and write a new class for EVERY button we make. We will use Anonymous Inner Classes to make our life easier Anonymous Class Allows you to declare and instantiate a class at the same time Makes code more concise and compact Great for one shot classes 43

Pushing Buttons Listeners How to create an anonymous inner class: Use them inside expressions: myesbutton.setonclicklistener(); Use the new keyword to create the instance of the class you are defining: Because View.onClickListener is an interface, we need to implement any required methods: myesbutton.setonclicklistener( new View.OnClickListener(){ @Override public void onclick(view v){ //Do Something } }); Pushing Buttons Listeners myesbutton = (Button) findviewbyid(r.id.button_yes); mnobutton = (Button) findviewbyid(r.id.button_no); myesbutton.setonclicklistener( new OnClickListener(){ @Override public void onclick(view arg0) {//Do Something} }); mnobutton.setonclicklistener( new OnClickListener(){ @Override public void onclick(view arg0) {//Do Something} }); 44

Pushing Buttons Listeners You could created a named class if you wanted Anonymous inner classes have the benefit of being right where they are used In addition, most of the time you don t reuse these Listener class again Pushing Buttons Toasts When the user presses yes or no we want to inform them about their decision Toasts create temporary pop-ups that don t require any user interaction This is a toast 45

Pushing Buttons Toasts The Toast class has a public static method called maketext() There are two versions of maketext: Toast.makeText( Toast.makeText( Context context, CharSequence text, int duration); Context context, int resid, int duration); Pushing Buttons Toasts Lets put a toast in the yes and no listeners: myesbutton.setonclicklistener( new OnClickListener(){ @Override public void onclick(view arg0) { Toast.makeText(BlankActivity.this, Woo Hoo!?", Toast.LENGTH_SHORT).show(); } }); mnobutton.setonclicklistener( new OnClickListener(){ @Override public void onclick(view arg0) { Toast.makeText(BlankActivity.this, "Well I don't like you either!", Toast.LENGTH_SHORT).show(); } }); 46

Pushing Buttons Build and Run! Build and run your app either on the emulator or on your personal device. Pushing Buttons How was it Built? Your project is continually built automatically as you work Android takes the resources, code and AndroidManifest.xml and converts it into an.apk file This file is signed with a debug key To distribute an.apk to everyone else, you need a release key When your activity is launched, the setcontentview inflates your XML code into actual instances as defined in the layout 47

Lab: Experiment with Pushing Buttons 1. Change the layout, try gravity settings 2. Try modifying a text field in the listener instead of a toast 3. Get it to run on your emulator and device Goals: Get comfy with Android Studio Become familiar with layouts and accessing resources from the Java side 48