ANDROID A FIRST PROGRAM L Grewe Using Android

  • Slides: 39
Download presentation
ANDROID – A FIRST PROGRAM L. Grewe

ANDROID – A FIRST PROGRAM L. Grewe

Using Android. Studio –basic Android Lets do a “Hello World Project” Start up Android.

Using Android. Studio –basic Android Lets do a “Hello World Project” Start up Android. Studio (assume you have installed with Android support)

Hello World Project – Android Studio 1. 2. 3. 4. 5. App name, package

Hello World Project – Android Studio 1. 2. 3. 4. 5. App name, package Target Activity type Name of Activity Now finish to setup

Hello World Project---basic folders &files Folders • Number of folders and files are autogenerated

Hello World Project---basic folders &files Folders • Number of folders and files are autogenerated when you create a project File of note Android. Manifest. xml – like a ship’s manifest it tells us the components of our app

Project basics…. Android Studio manifests/Android. Manifest. xml: an XML file describing the application being

Project basics…. Android Studio manifests/Android. Manifest. xml: an XML file describing the application being built and what components – activities, services, etc. – are being supplied by that application java/: holds the Java source code for the application res/: contains layout files drawable =icons menus

Project basics…. Android Studio Gradle Scripts/: an gradle script for compiling the application and

Project basics…. Android Studio Gradle Scripts/: an gradle script for compiling the application and installing it on the device (integrated with IDE—don’t see it there) gradle. properties: a property file used by the compiler

Manifest file – Android. Manifest. xml an XML file describing the application being built

Manifest file – Android. Manifest. xml an XML file describing the application being built and what components – activities, services, etc. – are being supplied by that application Initially created by IDE must declare all activities, services, broadcast receivers and content provider of the application. must contain the required permissions for the application. For example if the application requires network access it must be specified here.

Hello World Project – Android. Manifest. xml Define Application –see res/strings. xml Manifest file

Hello World Project – Android. Manifest. xml Define Application –see res/strings. xml Manifest file –see res/drawable-resolution/icon. png <? xml version="1. 0" encoding="utf-8"? > <manifest xmlns: android="http: //schemas. android. com/apk/res/android" package="com. example. helloworldandroid" android: version. Code="1" android: version. Name="1. 0"> <application android: icon="@drawable/icon" android: label="@string/app_name"> <activity android: name=". Hello. World. Android" android: label="@string/app_name"> <intent-filter> <action android: name="android. intent. action. MAIN" /> <category android: name="android. intent. category. LAUNCHER" /> </intent-filter> </activity> </application> Here have intent created for <uses-sdk android: min. Sdk. Version="4" /> This acitivity that is associated with </manifest> launch of application

The Layout Interface specifications

The Layout Interface specifications

Interface ---2 options Do it with XML file(s) Many modern frameworks whether for mobile

Interface ---2 options Do it with XML file(s) Many modern frameworks whether for mobile programming like Android or i. OS or for other platforms have gone to specifying GUI (graphical user interface) elements in static XML files rather than programming source code (like java). The reason –it allows separation of the look (view) from how the code works (model and controller). Have you ever heard of Model View Controller –it is a famous software engineering framework that programmers try to achieve in their software systems. Do it with Java code. This has similarities if you have created desktop GUI Java applications

OPTION 1: The Layout with XML We are going to discuss a specific resource

OPTION 1: The Layout with XML We are going to discuss a specific resource in the res folder res/layout/activity_main. x ml

The Layout-the interface res/layout/main. xml = contains layout for interface <? xml version="1. 0"

The Layout-the interface res/layout/main. xml = contains layout for interface <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent" > <Text. View android: layout_width="fill_parent" android: layout_height="wrap_content" android: text="@string/hello" /> </Linear. Layout> The above will create an interface in vertical (versus portrait) mode that fills the parent Both in width and write and wraps and content as necessary.

The Layout-the interface res/layout/main. xml <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns:

The Layout-the interface res/layout/main. xml <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent" > android: orientation = vertical (versus portrait) mode. that fills the parent both in width and write and wraps and content as necessary. Vertical Landscape

Hello World Project Creating a Layout file— 2 options 1) Do it manually –type

Hello World Project Creating a Layout file— 2 options 1) Do it manually –type it in Layout file 2) For Layouts corresponding to GUIs You have a drag and drop option we will learn about in a later lecture <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent" > <Text. View android: layout_width="fill_parent" android: layout_height="wrap_content" android: text="@string/hello" /> </Linear. Layout> This adds a “Text. View” to the interface and this has the text referenced by @string/hello in it.

Using IDE to Visually Create XML file Visual creation of XML file Android. Studio:

Using IDE to Visually Create XML file Visual creation of XML file Android. Studio: New-> Layout resource file Select layout (root) &qualifiers as needed drag & drop

Visually Creating XML interface I dragged and dropped an Edit. Text view and a

Visually Creating XML interface I dragged and dropped an Edit. Text view and a Button. Below I show you the corresponding code. res/layout/main 2. xml <? xml version="1. 0" encoding="utf-8"? > <Absolute. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="match_parent" android: layout_height="match_parent"> <Edit. Text android: text="@string/hello" android: id="@+id/edit. Text 1" android: input. Type="text. Multi. Line" android: layout_width="169 dp" android: layout_height="115 dp" android: layout_x="11 dp" android: layout_y="20 dp"></Edit. Text> <Button android: id="@+id/button 1" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text="Button" android: layout_x="27 dp" android: layout_y="146 dp"></Button> </Absolute. Layout>

Lets look at the “Main” class It is an Activity is a class in

Lets look at the “Main” class It is an Activity is a class in the Android sdk (android. app. Activity) It represents us now the main application itself —we will learn more about what this means in a near future lecture –remember we are at the beginning!

Create an Activity with simple text Interface ……first An Android user interface is composed

Create an Activity with simple text Interface ……first An Android user interface is composed of hierarchies of objects called Views. A View is a drawable object used as an element in your UI layout, such as a button, image, or In the next code will create a text label. Each of these objects is a subclass of the View class and the subclass that handles text is Text. View.

Hello World Project – here we are creating interface with programatically/code Helloworld. java package

Hello World Project – here we are creating interface with programatically/code Helloworld. java package com. teach. helloworld; import android. app. Activity; import android. os. Bundle; create a Text. View with the class constructor, which accepts an Android Context instance as its parameter. • Context is a handle to the system • provides services like resolving resources, • obtaining access to databases and preferences, etc. The Activity class inherits from Context, and because your Hello. Android class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the Text. View. public class helloworld extends Activity { /** Called when the activity is first created. */ @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); Text. View tv = new Text. View(this); tv. set. Text("Hello, Android. . . Lynne"); set. Content. View(tv); } } text content is set with set. Text(Char. Sequence) pass the Text. View to set. Content. View() in order to display it as the content for the Activity UI.

What we just learned You will have a class created for you that is

What we just learned You will have a class created for you that is your android application, i. e. “ helloworld” and it extends Activity Your application is an Activity and that also descends from Content Context = class that gives us access to System • • provides services like resolving resources, obtaining access to databases and preferences, etc View = is a GUI element, there are different kinds like the Text. View we are using • . constructor needs Context instance (we used our App)

R. java Automatically created by IDE when created project

R. java Automatically created by IDE when created project

Hello World Project R. Java == generated by project, this points to various resources

Hello World Project R. Java == generated by project, this points to various resources in your project see res folder. DO NOT EDIT THIS –unless you know what you are doing. /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com. example. helloworldandroid; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0 x 7 f 020000; } public static final class id { public static final int button 1=0 x 7 f 050001; public static final int edit. Text 1=0 x 7 f 050000; } public static final class layout { public static final int main=0 x 7 f 030000; public static final int main 2=0 x 7 f 030001; } public static final class string { public static final int app_name=0 x 7 f 040001; public static final int hello=0 x 7 f 040000; } }

TIP: sometimes when you are compiling your code you can have problems with the

TIP: sometimes when you are compiling your code you can have problems with the R. java file (which you DON’T edit) –what is going on? Somehow the R. java is out of sync with the project resources…. . WHAT TO DO? do a “Build->Clean Project” and it will regenerate R. java for you Why have R. java? It is used it in your code to point to resources. Lets look at an example where we alter our on. Create method to point to the interface described in the res/layout/main. xml file…. so now interface specified with XML and not programmatically with code.

Where is R. java Eclipse: gens/R. java Android Studio: build/generated/source/r/debug/your-package name/R. java (Example: C:

Where is R. java Eclipse: gens/R. java Android Studio: build/generated/source/r/debug/your-package name/R. java (Example: C: UsersLynneAndroid. Studio. ProjectsHello. World. Androidappbuil dgeneratedsourcerdebugcomexamplelynnehelloworldandroid) Android studio: you can not see the R. java in IDE Go to file system

Alter your Activity to Use an XML layout file package com. example. helloandroid; import

Alter your Activity to Use an XML layout file package com. example. helloandroid; import android. app. Activity; import android. os. Bundle; Now going to change the code so it uses instead an XML file for its intervace public class Hello. Android extends Activity { /** Called when the activity is first created. */ @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); This line of code says set. Content. View(R. layout. main); use the xml layout file called } main. xml that is pointed to } inside your R. java file in memory

Interfaces ---XML-based layout Previous Hello. World example has interface created in java code. ALTERNATIVE:

Interfaces ---XML-based layout Previous Hello. World example has interface created in java code. ALTERNATIVE: XML-based layout files. Example that duplicates previous. <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout………. > <Text. View xmlns: android="http: //schemas. android. com/apk/res/android" android: layout_width="fill_parent" android: layout_height="fill_parent" android: text="@string/hello"/> Above located in res/layout/main. xml Here is our main. xml file that will be used and do the same thing as our previous java code –show a Text. View

XML interface Lets understand the XML Tag used to describe our Text. View <Text.

XML interface Lets understand the XML Tag used to describe our Text. View <Text. View xmlns: android="http: //schemas. android. com/apk/res/android" android: layout_width="fill_parent" android: layout_height="fill_parent" android: text="@string/hello"/> xmlns: android XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. android: layout_width This attribute defines how much of the available width on the screen this View should consume. As it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means. android: layout_height This is just like android: layout_width, except that it refers to available screen height. android: text This sets the text that the Text. View should display. In this example, you use a string resource instead of a hard-coded string value. The helloastring defined in the---aren’t res/values/strings. xml file. have an API online to Wow! That’s lot tois remember you glad we look it up ---better yet is the drag and drop option to make interfaces!!!

More on resources The res directory

More on resources The res directory

We mentioned res folder Android Studio

We mentioned res folder Android Studio

res/ directory res/layout/ : contains one or more xml files that define interfaces res/values/strings.

res/ directory res/layout/ : contains one or more xml files that define interfaces res/values/strings. xml : file where you specify strings (constants) that you can use in your program res/drawable-* : gives file use for different resolutions like icon. jpg. *=hdpi (high), mdpi(medium), ldpi (low). Depends on device what mode it can/may be running in. res/menu/ : contains one or more xml files for menus

Event Handling So we have an interface what can we do with it. Event

Event Handling So we have an interface what can we do with it. Event Handling = code that responds when “events” happen. For GUI elements we usually have events associated with them. For example, a button has the event of hitting the button.

Widget : Views that have events For a list of the widgets provided by

Widget : Views that have events For a list of the widgets provided by Android, see the android. widget package. Some Examples Button Check. Box Date. Picker Edit. Text Image. View Search. View Spinner There are more ---here a few.

3 steps: 1) Decide what events to respond to 2) Create a listener to

3 steps: 1) Decide what events to respond to 2) Create a listener to respond to each event 3) Register the listener to the corresponding widget Event Handling Decide what Widgets who’s events to process Define an event listener and register it with the View. On. Click. Listener (for handling "clicks" on a View), View. On. Touch. Listener (for handling touch screen events in a View), and View. On. Key. Listener (for handling device key presses within a View) http: //developer. android. com/guide/topics/ ui/ui-events. html details more

Lets add a Button to a programbased interface Step 1: Add button Step 2:

Lets add a Button to a programbased interface Step 1: Add button Step 2: Register Event Handler TWO OPTIONS – separate class to handle event(s), OR have the Activity containing the button do the event handling Step 3: Implement Event Handler…for a Button means implementing the View. On. Click. Listener interface

Event handling done by Activity itself –one option Here code to handle is inside

Event handling done by Activity itself –one option Here code to handle is inside Activity itself public class Example. Activity extends Activity implements On. Click. Listener { protected void on. Create(Bundle saved. Values) { . . . Button button = (Button)find. View. By. Id(R. id. corky); button. set. On. Click. Listener(this); } // Implement the On. Click. Listener callback public void on. Click(View v) { // do something when the button is clicked }. . . } This option is okay only if the event handling code is simple and you will not reuse it ever ---if the code is longer or will reuse make a separate class

Event Handling - here have a SEPARATE class EVENT HANDLING CODE in separate object

Event Handling - here have a SEPARATE class EVENT HANDLING CODE in separate object m. Corky. Listner // Create an anonymous implementation of On. Click. Listener private On. Click. Listener m. Corky. Listener = new On. Click. Listener() { public void on. Click(View v) { // do something when the button is clicked } }; Better for readability and reuse //Now inside your Activity class protected void on. Create(Bundle saved. Values) {. . . // STEP 1: Capture our button from layout Button button = (Button)find. View. By. Id(R. id. corky); // STEP 2: Register the on. Click listener with the implementation above button. set. On. Click. Listener(m. Corky. Listener); . . . }

Run your code Depends on IDE

Run your code Depends on IDE

Running code Will Run in the Emulator Android Studio: Run->”Run app” or “Debug App”

Running code Will Run in the Emulator Android Studio: Run->”Run app” or “Debug App” You should learn to run both on the emulator AND on a physical device. TO use features of a phone like GPS, etc. it is often required to run on a phone

Running code TIP: Emulator can take a long time to load at first----be patient

Running code TIP: Emulator can take a long time to load at first----be patient and keep it up---just re-run after changes and won’t have to relaunch emulator, will just load up new app. Look if you have Intell Virtualization speed up, check out GPU and snapshot options – search online for current info on these tips