Download Android - It works!

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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 TechCrunch (by the
developer of the SMS/MMS app Emu:
The Fallacy of Andoid First
Basics
 Apps are composed of activities and layouts
 an activity is an instance of the activity class
 manages user interaction with a screen of info
 subclass it to implement app functionality
 may have many activities for a complex app
 a layout defines a set of user interface objects and their
position on the screen
 uses XML
 each definition creates an object on the screen
Create the project
 in Eclipse:




File->New->Android Application
name: GeoQuiz
package: edu.ithaca.android.geoquiz
Target SDK: API 16: Android 4.1 (Jelly Bean)
 doesn’t matter as long as you’ve downloaded this in Eclipse
 click next
Configuring the project
 unclick “Create custom launcher icon”
 leave “Create activity” checked
 uncheck “Mark this project as a library”
 check “Create Project in Workspace”
 should not have to change location
 uncheck “Add project to working sets”
 click next
Configuring Project
 click on “Blank Activity”
 click next
 Name the activity subclass QuizActivity
 convention to end name with “Activity” but not required
 layout name will fill in automagically. Provides recommended naming
style.
 click finish
Laying out the user interface
 Open the layout file
 in the folder res/layout
 named activity_quiz.xml
 select the “activity_quiz.xml” tab at the bottom of the middle screen of
Eclipse.
 we will ignore the graphical layout tool for now
 we will use this file to create our view.
 should have a framelayout




in the folder res/layout
for fragments or partial layouts
named fragment_quiz.xml
we will ignore this file; we’re not going to use fragments
Default Layout (part 1)
in activity_quiz.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="edu.ithaca.geoquiz4.QuizActivity"
tools:ignore="MergeRootFrame" />
Default Layout (part 1)
in fragment_quiz.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="edu.ithaca.geoquiz4.QuizActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
Default Layout (part 2)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
Layout file
 default fragment_quiz.xml file has two widgets
 RelativeLayout
 TextView
 Widgets are the components of a view
 every widget is an instance of the View class or one of its
subclasses
 Click the Graphical Layout tab at bottom to see how the
layout looks
Layout
 QuizActivity requires 5 widgets:




a vertical LinearLayout
a TextView
a horizontal LinearLayout
two Buttons
Layout
Overwrite all the text in activity_quiz.xml with this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
There will be errors!
<TextView
android:text="@string/question_text”
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/true_button" />
<Button
android:id="@+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/false_button" />
</LinearLayout>
</LinearLayout>
+ sign means that you are creating
the resource not just referencing it
The view hierarchy
Widget Attributes
 android:orientation
 determines whether the children appear vertically or
horizontally
 the order in which children are defined determines the order in
which they appear on screen.
 in vertical, first child is topmost
 in horizontal, first child is leftmost (unless right-to-left language)
Widget Attributes
 android:text
 tells widget what text to display
 not literal strings (thought they could be)
 instead references to string resources
 a string that lives in a separate XML file called the strings file
 allows for easy localization
String Resources
 every project has a default strings file named strings.xml
 open the strings.xml file in res/values
 click on strings.xml tab at bottom
 remove the hello_world string, add three new strings
<string name="app_name">GeoQuiz</string>
<string name="question_text">The Pacific Ocean is
larger than the Atlantic Ocean.</string>
<string name="true_button">True</string>
<string name="false_button">False</string>
<string name="correct_toast">Correct!</string>
<string name="incorrect_toast">Incorrect!</string>
<string name="menu_settings">Settings</string>
keep the menu_settings or you’ll get lots of errors!
String Resources
 whenever you refer to @string/false_button in any
XML file in the GeoQuiz project, get “False” at runtime.
 save strings.xml
 errors in fragment_quiz.xml should go away
 may get warnings; can ignore.
 You can have multiple strings files in your project




must be in res/values
must have a resources root element
must contain child string elements
your strings will be found automagically
Creating View Objects
 How do XML elements become View objects?
 see code on next slide
 contains two Activity methods
 onCreate(Bundle)
 called when an instance of the activity subclass





(QuizActivity) is created.
calls method setContentView(int layoutResID)
this method inflates a layout and puts it on the screen
also asks the fragment manager to add the appropriate
fragments
each widget is instantiated as defined by its attributes
you specify which layout by passing the layout’s resource ID
(see later)
 onCreateOptionsMenu(Menu)
Creating View Objects
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
Delete this method; we won’t use fragments!
Resources and resource IDS
 resource: a piece of your app that is not code
 images, audio files, XML files
 resources live in a subdirectory of the res directory
 activity_quiz.xml lives in res/layout/
 strings file lives in res/values/
Resources and resource IDS
 resource: can see by opening the file R.java
 it’s in the gen/edu.ithaca.android.geoquiz
directory
 the edu.ithaca.android.geoquiz name depends on what
you named your package.
 this file is generated by the build process
 won’t be there until you build!
 you should see a value similar to
public static final int activity_quiz=0x7f030000;
Resources
 To access a resource in code use its resourceID
 resource for our layout is R.layout.activity_quiz
 Android generates resource IDs for entire layouts and each
string
 but not individual widgets
 to generate a resourceID for a widget must include an
android:id attribute in the widget’s definition
 For each button add the attribute:
android:id="@+id/true_button”
or
android:id="@+id/false_button"
the + sign means to create the id
Wiring up widgets
 Can access buttons via their resource IDs
 Add the bold lines to QuizActivity:
the m prefix is an android convention
public class QuizActivity extends Activity {
private Button mTrueButton;
private Button mFalseButton;
these will cause errors:
the Button type needs to be
imported!
see next slide!
@Override
protected void onCreate(Bundle savedInstanceState) {
Wiring up widgets
 To fix the import error can organize your imports
 To organize press:
 Command+Shift+O
 Ctrl+Shift+O
on mac
on windows/linux
 this will put in the necessary imports
Wiring up widgets
 To wire up buttons:
 get references to the inflated View objects
 set listeners on those objects to respond to user
actions
Get ref to widgets
 Can get a reference to an inflated widget by calling:
 public View findViewById(int id)
 this method accepts a resource ID of a widget
 it returns a View object
 Add to QuizActivity.java
 see next slide
Get ref to widgets
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton =
(Button)findViewById(R.id.true_button);
mFalseButton =
(Button)findViewById(R.id.false_button);
return true;
}
Setting Listeners
 Android apps are event driven
 When app is waiting for a specific event it is listening
for that event
 A listener is an object that implements a listener
interface for that event.
 listener interfaces are provided by Android for most
events
Setting Listeners
 Our app: want to listen for a mouse click
 Must implement the View.OnClickListener
interface
Setting Listeners
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
We’ll fill this in shortly!
mFalseButton = (Button)findViewById(R.id.false_button);
return true;
}
Anonymous Classes
 The listener on the last slide is an anonymous inner
class
 Most listeners in Android use this technique
 The anonymous inner class implements the
OnClickListener interface.
 means it must implement the interface methods
 in this case, there is only one: OnClick(View)
 Must set a similar class for the false button (next slide)
Setting Listeners
// mTrueButton code is still here, I just took it out to save room
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return true;
}
We’ll fill this in shortly!
Toasts
 A pop-up message in Android is called a toast
 A toast is a short message that informs the user of
something but does not require any input or action.
 We’ll make toasts that announce whether the user
answered correctly or not.
Toasts
 To make a toast call the following method from the Toast
class:
public static toast Toast makeText(Context
context, int resId, int duration)
 The Context parameter is typically an instance of an
Activity class.
 The second parameter is the resource ID of the string that
the Toast will display
 needs the Context to find and use the string’s resource ID
 Third parameter is one of two Toast constants that specify
how long the toast should be visible
Toasts
 After you make a Toast, use Toast.show() to get it on
the screen.
 see next slide
Making Toasts
for mTrueButton handler:
QuizActivity.this indicates
the correct context
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
Toast.LENGTH_SHORT).show();
}
Cannot just say “this”
because we’re inside an
anonymous class!
Making Toasts
for mFalseButton handler:
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT).show();
}
Run
 right click on name and choose
Run As->Android Application
 To run on device,
 on a Mac just connect device via USB.
 on Windows may need to install the abd (Android Debug
Bridge).
 may have to download from your device manufacturer’s
website
 must set device up (see next slide).
Setting up device Step 1
 Must set up device to accept applications that are not
from Google Play
 if device is running Android 4.1 or earlier, go to
SettingsApplications. Make sure Unknown
sources is checked.
 if device is running Android 4.2 or later, go to
SettingsSecurity. Make sure Unknown sources is
checked.
Setting up device Step 2
 Must enable USB debugging in the device.
 Android 4.0 and earlier:
SettingsApplicationsDevelopment and
enable USB debugging
 Android 4.1 or later. Must enable
developer options.
 Go to SettingsAbout
Tablet/phone and press
Build Number 7 times.
 Return to Settings see Developer
enable USB Debugging.
Options and
Debugging
 To see what’s happening on the device or the emulator,
see the LogCat window at the bottom of Eclipse (next
to the console window).
 If it’s not showing go to Window  Show View 
Other
 Expand Android and double-click on LogCat