Arquivo da tag: Android

[Android] Notes About View, Layout and Adapters

View
Key building block for UI components
Occupy a rectangular space on screen
Responsible for drawing themselves and for handling events

Common View Operations
Set visibility: show or hide view
Set Checked state
Set Listeners: Code that should be executed when specific events occur
Set properties: opacity, background, rotation
Manage input focus: allow view to take focus, request focus

View Event Sources
User interaction
- Touch
- Keyboard/trackball/D-pad
System control
- Lifecycle changes

Displaying Views
Views are organized in a Tree
Displaying has multiple steps
Measure – get dimensions of each View
Layout – Position each View
Draw – Draw each view

ViewGroup
An invisible View that contains other views
Used for grouping & organizing a set of views
Base class for view containers & layouts

Adapters & AdapterViews
AdapterViews are views whose children and data are managed by an Adapter
Adapter manages the data and provides data views to AdapterView
AdapterView displays the data Views

Layout
A generic ViewGroup that defines a structure for the Views it contains

LinearLayout
Child views arranged in a single horizontal or vertical row

RelativeLayout
Child views are positioned relative to each other and to parent view

TableLayout
Child views arranged into rows & columns

GridView
Child views arranged in a two-dimensional, scrollable grid

Menus and ActionBar
Activities support menus
Activities can
- Add items to a menu
- handle clicks on the menu items

Menu Types
Options
- menu shown when user presses the menu button
Context
- View-specific menu shown when user touches and holds the view
Submenu
- A menu activated when user touches a visible menu item

Creating Menus
Define menu resource in XML file
- Store in res/menu/filename.xml
Inflate menu resource using Menu
Inflater in onCreate…Menu() methods
Handling item selection in appropriate on…ItemsSelected() methods

Menus
Many other features supported
- Grouping menu items
- Binding shortcut keys to menu items
- Binding Intents to menu items

ActionBar
Similar to Application Bar in many desktop applications
Enables quick Access to common operations

ActionBar.Tab
Screen is divided into tab & content areas
Allows multiple Fragments to share single content area
Each tab is associated with one Fragment
Exactly one tab is selected at any given time
Fragment corresponding to the selected tab is visible in the content area

Dialogs
Independent subwindows used by Activities to communicate with user
- AlertDialog
- ProgressDialog
- DatePickerDialog
- TimePickerDialog

Questions

An application's user interface can include more than just the visual components on the display screen.
True

Which of the following statements correctly describe the View class.
A View is a basic building block of user interfaces.
A View is responsible for drawing itself.
A View is responsible for handling events directed to it.

AdapterViews collaborate with Adapters to manage and display information. Which of the following statements are true of the Adapter interface? See: http://developer.android.com/reference/android/widget/Adapter.html for further documentation.
Adapters provide data using methods such as getCount() and getItem().
Adapters provide Views to the AdapterView.

Layouts are ViewGroups that arrange or organize the position of their child Views.
True

The child Views contained in a LinearLayout can be made to overlap each other by specifying a fractional value for android:layout_weight. See: http://developer.android.com/reference/android/widget/LinearLayout.html for more information.
False

The UIGridView application reads a bunch of Bitmaps into the application and then displays them. For example, one Bitmap is stored in a file called image1.jpg. What Java identifier was used to access this Bitmap file?
R.drawable.image1

Which one of the following statements correctly describes a difference between Context Menus and Options Menus?
Context Menus are generally associated with individual Views, while Options Menus are generally associated with the entire application.

If your application contains a Fragment and that Fragment wants to place actions in the Action Bar, which of the following methods will that Fragment likely call or implement?
onCreateOptionsMenu().
setHasOptionsMenu().

The example application you just saw created and displayed an AlertDialogFragment. This Object was created by using an AlertDialog.Builder Object. Take a look at the documentation for AlertDialog.Builder. Which class is most often used as the return type of this class' methods?
See: http://developer.android.com/reference/android/app/AlertDialog.Builder.html.
AlertDialog.Builder.

Which of the following statements describe key responsibilities of a View?
To respond to events directed to them.
To draw themselves.

Which of the following are properties that can be set on a View?
Position.
Visibility.
Opacity (transparency).

An AutoCompleteTextView is a subclass of ViewGroup. Hint: Consult the Android documentation at http://developer.android.com/reference/classes.html
False

Which of the following statements describe the relationship between and AdapterView and its Adapter?
The Adapter manages a data set for the AdapterView.
Adapters can notify the AdapterView when the Adapter data changes.

Suppose a layout file declares a LinearLayout called LL that contains two child Views, View1 and View2. In the layout file View1 is given an android:layout_weight of 2 and a layout_width of 0dp. View 2 is given an android:layout_weight of 3 and a layout_width of 0dp. In this example, which of the following statements must be true?
View 2 takes up 3/5 of LL's width.

When a user long clicks on a View that has registered to show a Context Menu, which one of the following methods will be called?
onCreateContextMenu().

Suppose that an application wants to create and display a Dialog. If the application embodies the Dialog in a DialogFragment, which DialogFragment method will it call to make the Dialog visible to the user?
show()

The ActionBar has four functional areas: The App icon, a View control area, an Action Buttons area and an Action Overflow area. What is the purpose of the Action Overflow area? See; http://developer.android.com/design/patterns/actionbar.html for more information.
When Action Buttons cannot fit in or should not be placed on the Action Bar, they are displayed in a separate View that is accessible by touching the Action Overflow area.

Enjoy
Marcos Carvalho

[Android] Notes About Intent Class, Permissions and Fragment Class

Intent Class
A data structure that represents
- An operation to be performed
- An event that has occurred

Intent as desired operations
Intents provide a flexible language for specifying operations to be performed.
Intent is constructed by one component that wants some work done
Received by one activity that can perform that works

Intent Fiels
Action
- action_dial - dial a number
- action_edit - display data to edit
- action_sync - synchronize device data with server
- action_main - start as initial activity of app
Data
- Data associated with the intent
- Formatted as a URI (uniform resource identifier)
Category
- Additional information about the components that can handle the intent
Type
- Specifies the MIME type of the intent data
Component
- The component that should receive this intent
- Use this when there's exactly one component that should receive the intent
Extras
- Add'l information associated with intent
- treated as a map
Flags
- Specify how intent should be handled

The target activity
Can be named explicitly by setting the intent's component
Can be determined implicitly

Implicit activation
When the activity to be activated is not explicitly named, Android tries to find activities that match the intent
This process is called intent resolution process
- An intent describing a desired operation
- IntentFilters which describe which operations an activity can handle
-- Specified either in AndroidManifest.xml or programmatically

Intent Resolution Data
Action
Data (Both URI & TYPE)
Category

Priority
Android:Priority - Priority given to the parent component when handling matching intents
Causes Android to prefer one activity over another
Value should be greater than 1000 & less than 1000
Hiver values represent higher priority

Permissions
Android protects resources & data with permissions
Used to limit access to:
- User information
- cost-sensitive API's
- System resources
Permissions are represented as strings
In AndroidManifest.xml, apps declare permissions
They require of other components

Using Permissions
Apps specify permissions they use througha <uses-permission> tag
Users must accept these permissions before an application can be installed

Defining Permissions
Suppose your application performs a privileged/dangerous operation
You might not want to allow just any application to invoke yours
So you can define & enforce your own permission

Component Permissions
Individual components can set their own permissions, restricting which other components can access them
Component permissions take precedence over application-level permissions

Activity permissions
restricts which components can start the associated activity
Checked within execution of
- startActivity()
- startActivityForResult()
Throws SecutityException on permissions failure
onCreateView() must return the View at the root of the Fragments's layout
This view is added to the containing activity

Fragment Class
Represents a behavior / portion of UI within an activity
Multiple fragments can be embedded in an activity to create a Multi-pane UI
A single fragment can be reused across multiple activities
Fragment lifecycle is coordinated with the lifecycle of its containing activity
Fragments have their own lifecycles and receive their own callbaks

Adding Fragments to Activities
Two general ways to add fragments to an activity's layout
- Declare it statically in the activity's layout file
- Add it programmatically using the FragmentManager
Layout can be inflated/implemented in onCreateView()

Adding Fragments Dynamically (Frame layout)
While an activity's running you can add a fragment to it's layout
- Get reference to the FragmentManager
- Begin a FragmentTransaction
- Add the fragment
- Commit the FragmentTransaction

Dynamic Layout
Fragment transactions allow you to dynamically change your app's user interface
Can make the interface more fluid & take better advantage of available screen space

Configuration Changes
If you call setRetainInstance(true), Android won't destroy the Fragment on configuration changes
Results in some changes to lifecycle callback sequence
onDestroy() will not be called
onCreate() will not be called

Questions

Which of the following statements describe common uses of the Intent class?
To specify an operation to be performed.
To represent an event that has occurred.

If you want to send a message to a particular person using an Intent with the Intent.ACTION_SENDTO action, what one other piece of Intent information do you have to set?
See: http://developer.android.com/reference/android/content/Intent.html#ACTION_SENDTO for more information.
Data.

Which one of the following flags will help you get more information about how Android determines which Activities can respond to a given Intent?
Intent.FLAG_DEBUG_LOG_RESOLUTION.

Which of the following Intent fields are used as match criteria during Intent resolution?
Category.
Action.
Data

Which of the following describe situations where permissions might be used?
To restrict access to costly operations.
To restrict accesps to device hardware features.
To restrict access to user data.

Which XML tag does an application use to specify permissions that the device's user must grant to the application before that application can run on the user's device.
<uses-permission>

Which XML tag or attribute is used to specify an application-specific permission that an application may require of any other application that wants to interact with it?
<permission>

Which Exception is thrown if one Activity tries to start another Activity for which it does not have the appropriate permissions?
SecurityException.

When designing an application's user interface, it's a good practice to design a single, identical user interface for both Tablets and Phones.
False

Which one of the following Fragment lifecycle callback methods occurs at the earliest point in the Fragment lifecycle?
onAttach().

In which method does a Fragment normally create its user interface?
onCreateView().

When an application programatically adds a Fragment to an Activity, it normally performs the four steps shown below. Which of these steps is done last?
Commit the FragmentTransaction

When a Fragment is programmatically added to an Activity, by default Android adds the new Fragment to the Task backstack.
False

Which one of the following Fragment methods tells Android not to destroy a Fragment when a device configuration change occurs?
setRetainInstance().

Suppose that an application includes an Activity named A, and that the application declares an <activity> tag for A within its AndroidManifest.xml file. If Activity A should be the main entry point for this application, then it will specify an <intent-filter> element, containing an <action> element. What value should you include to complete the following <action> element definition - <action android:name= "…."/>?
android.intent.action.MAIN

Suppose that an application includes an Activity named A and that the application declares an activity tag for A within its AndroidManifest.xml file. If Activity A will be the main entry point for its application and if an icon for this application/activity should appear in the top-level launcher, how should you complete the following <category> element - <category android:name="…"/>?
android.intent.category.LAUNCHER

The MapLocationFromContacts application created an Intent with the Action, Intent.ACTION_PICK and a with data URI representing the contacts database. It then invoked an Activity using startActivityForResult(). What type of data will the started Activity return?
A String Uri.

Suppose you create an application that uses the Vibration Service to make a device vibrate as a deadline approaches. To receive permission to use the Vibrator Service, you will need to add a <uses-permission> element to your application's AndroidManifest.xml file. What permission value should you use to complete the <uses-permission> element - <uses-permission android:name="…"/>?
See: http://developer.android.com/reference/android/Manifest.permission.html for more information.
android.permission.VIBRATE

Suppose you create an application that captures and stores personal information from the user, such as the medicines they are currently taking. Other applications may want to use this information and then provide add-on services over it, for example, to create 'time to take your pill' reminders. Which of the following tags would you put in your application's AndroidManifest.xml file to define a new application-specific permission for accessing your application.
<permission>.
The Fragment class is a subclass of the Activity class and replaces Activities on large screen devices such as Tablets.
False

In which method do Fragments typically create their user interfaces?
onCreateView().

Which of the following are good reasons for dynamically modifying application layouts at runtime, rather than by using static layout files.
Dynamic layouts can take advantage of contextual information that's not tracked by Android's configuration system (such as current location, usage time, or ambient light measurements).
Dynamically-created user interfaces can adapt to an application's runtime state, such as the amount of data that needs to be displayed at any one time.

Suppose you have an Activity that hosts a Fragment. This Fragment has invoked the setRetainInstance() method, passing in the parameter true. Which of the following Fragment lifecycle methods will not be called if the Activity is later killed and restarted due to a reconfiguration?
onDestroy().
onCreate().

Enjoy
Marcos Carvalho

Application Fundamental Android

Activity
Primary class for user interaction
Usually implements a single, focused task that the user can do

Service
Run in the background
To perform long-running operations
To support interaction with remote processes

BroadcastReceiver
Component that listens for and responds to events
The subscriber in publish/subscribe pattern
Events represented by the intent class and the broadcast
BroadcastReceiver receives and responds to broadcast event

Content Providers
Store & share data across applications
- Uses database-style interface
- Handles interprocess communication

Build-simplified-android

Participation in the build process will usually involve the four steps:
Define Resources
- Resources are non-source code entities
Implement Application Classes
Package Application
Install & run application

User Interface Layout
UI layout specified in xml files
XML files typically stored in res/layout/*.xml
Accessed in Java as: R.layout.layout_name
Can specify different layout files based on your device's orientation, screen size, etc.

R.java
At compilation time, resources are used to generate the R.java class
Java code uses the R class to access resources

Implement Classes
Usually involves at least one Activity
Activity initialization code usually in onCreate()
- Restore saved state
- Set content view
- Initialize UI elements
- Link UI elements to code Actions

Package Application
System packages application components & resources into a .apk file
Developers specify required application information in a file called
AndroidManifest.xml

Navigation through activities
Android supports navigation in several ways
Tasks
- a task is a set of related activities
- These related activities don't have to be part of the same application
- Most tasks start at the home screen
The task backstack
- when an activity is launched, it goes on top of the backstack
- when the activity is destroyed, it is popped off the backstack
Suspending & resuming activities

The Activity Lifecycle
Android-Activity-Lifecycle

onCreate()
Called when activity is created
Sets up initial state
- Call super.onCreate()
- Set the activity's content view
- Retain references to UI views as necessary
- Configure views as necessary

Starting Activities
Pass newly created intent to methods, such as:
startActivity()
startActivityForResult()
- Invokes a callback method when the called activity finishes to return a result

Questions

The Android documentation describes an Activity as "a single, focused thing that the user can do." Which one of the following statements best expresses why this statement might be somewhat ambiguous today?
Some devices, such as Tablets, are large enough to accommodate multiple screenfuls of data at one time.

Which one of the following statements might explain why the Music application plays songs using a Service, rather than by using one of its Activities?
The user might want to listen to music and do something else at the same time.

The MediaPlaybackService class that we looked at earlier in the lecture is a Service. Did you notice that it also contains a BroadcastReceiver called mIntentReceiver? What BroadcastReceiver method is overriden in the MediaPlaybackService.java file by mIntentReceiver?
onReceive

Which of the following statements about the ContentProvider class are true?
ContentProviders can perform interprocess communication.
ContentProviders encapsulate data sets.
Android supports several system-wide ContentProviders.

Which one of the four fundamental components of Android applications is designed to provide an interface to the user?
Activity

Which one of the four fundamental components of Android applications is designed to listen for and respond to events?
BroadcastReceiver

Which one of the four fundamental components of Android applications is designed for sharing data across applications?
ContentProvider

Which one of the four fundamental components of Android applications is designed to in-the-background and remote operations?
Service

Resources are non-source code entities within your application. Which of the following statements capture advantages of using resources, rather than managing entities directly within application source code?
Resources can be changed without recompiling source code.
Sets of resources can be created for different devices, user preferences, and devices configurations.

If you create a resource, such as a string resource, in an XML file, how can you access that resource in your Java code?
In your Java code you can refer to a string, called "string_name", as R.string.string_name.

In which level of the Android Platform would you find the Activity, Service, BroadcastReceiver, and ContentProvider classes?
The Application Framework Layer

Customizing strings for different languages allows more people to use your application, but it's not always that easy to do. Have you thought about some of the difficulties that might come from trying to support users of many different languages? Which of the following might be examples of such difficulties?
Left-to-right vs. right to left ordering of words
Differing word lengths for the same concept.
Differing date and time formats.
Ensuring that the translation is correct.

In which directory did we put the main.xml layout file that specifies MapLocation's layout when the device is in landscape mode?
res/layout-land

The Button.onClickListener interface defines a "callback" method. A callback method is a method that will get called at a future time, in this case, whenever the user clicks on a particular Button. What is the name of the callback method where you put code to be executed when a user clicks on a Button?
onClick

In which method are Activities usually initialized?
onCreate

Which of the following are examples of element tags that you might find in an AndroidManifest.xml file? See: http://developer.android.com/guide/topics/manifest/manifest-intro.html for more information.
<application>
<uses-sdk>

Which of the following are advantages of using an emulator instead of using a device?
You don't have to buy an actual device.
The emulated hardware is reconfigurable.
Changes to the emulator state don't make permanent changes to a device.

Which one of the following statements best captures a common design theme or principle for Android Activities?
Each Activity should support one focused thing that the user can do.

Which one of the following steps is typically done in onCreate()?
Set the Activity's content view.

When an Activity calls startActivityForResult(), it will eventually receive a callback to which of its methods?
onActivityResult().

When one Activity wants to start another activity it creates an Object that specifies which Activity it wants to start. What is the type of this Object?
Intent

Enjoy
Marcos Carvalho

Notes About Android Course

The Android Platform comprises several components.
Software Developers Kit
Software Stack
Documentation

Android's Linux Kernel is not exactly the same as the Linux Kernels typically running on desktop machines. Why would Android make its own Linux Kernel?
Mobile devices require features not usually needed on traditional desktop devices.

In which of the following programming languages are Android's Native libraries typically written?
C/C++

The Resource Manager helps with internationalizing applications. Which of the following might explain why that's important to Android developers?
Android phones and applications are sold to and used by people who speak languages other than English.

Which of following kinds of information does the Location Manager provide to applications?
User movement.
User location.

Enjoy
Marcos Carvalho