<Professional Android 4 Application Development> - Note 02

来源:互联网 发布:德拉蒙德格林体测数据 编辑:程序博客网 时间:2024/04/25 16:18

Chapter 4: Building User Interfaces


FUNDAMENTAL ANDROID UI DESIGN

  • Views — Views are the base class for all visual interface elements (commonly known as controls or widgets). All UI controls, including the layout classes, are derived from View.
  • View Groups
  • Fragments
  • Activities — Activities, described in detail in the previous chapter, represent the window, or screen, being displayed. Activities are the Android equivalent of Forms in traditional Windows desktop development. To display a UI, you assign a View (usually a layout or Fragment) to an Activity.


ANDROID USER INTERFACE FUNDAMENTALS

All visual components in Android descend from the View class and are referred to generically as Views.

The ViewGroup class is an extension of View designed to contain multiple Views.


Assigning User Interfaces to Activities

A new Activity starts with a temptingly empty screen onto which you place your UI. To do so, call setContentView in overridden onCreate handler, passing in the View instance, or layout resource, to display.


The setContentView method accepts either a layout's resource ID or a single View instance.


public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}


Once a Fragment has been inflated into an Activity, the Views it contains become part of that Activity's View hierarchy. As a result you can find any of its child Views from within the parent Activity, using findViewById as described previously.


INTRODUCING LAYOUTS

Layout Managers (or simply layouts) are extensions of the ViewGroup class and are used to position child Views within your UI. Layouts can be nested, letting you create arbitrarily complex UIs using a combination of layouts.


The following list includes some of the most commonly used layout classes available in the Android SDK:

  • FrameLayout
  • LinearLayout
  • RelativeLayout
  • GridLayout


Defining Layouts

The preferred way to define a layout is by using XML external resources.


Using Layouts to Create Device Independent User Interfaces


Optimizing Layouts


Redundant Layout Containers Are Redundant


Avoid Using Excessive Views

None of its layouts should include more than 80 Views.

To minimize the number of Views inflated within a complex layout, you can use a ViewStub, that is only inflated explicitly via the inflate method or when it's made visible.


Using Lint to Analyze Your Layouts

To assist you in optimizing your layout hierarchies, the Android SDK includes lint — a powerful tool that can be used to detect problems within you application, including layout performance issues.


INTRODUCING FRAGMENTS

Fragments enable you to divide your Activities into fully encapsulated reusable components, each with its own lifecycle and UI.



The Fragment Lifecycle

Fragments include a series of event handlers that mirror those in the Activity class. Fragments also include a number of additional callbacks that signal binding and unbinding the Fragment from its parent Activity.



Introducing the Fragment Manager

Each Activity includes a Fragment Manager to manage the Fragments it contains. The Fragment Manager provides the methods used to access the Fragments currently added to the Activity, and to perform Fragment Transaction to add, remove, and replace Fragments.


Adding Fragments to Activities

You can add the fragment tag within the Activity's layout in the XML.

Once the Fragment has been inflated, it becomes a View Group, laying out and managing its UI within the Activity.


INTRODUCING ADAPTERS

Adapters are used to bind data to View Groups that extend the AdapterView class (such as List View or Gallery).




Chapter 5: INTENTS AND BROADCAST RECEIVERS


INTRODUCING INTENTS

Intents are used as a message-passing mechanism that works both within your application and between applications.


Intent can:

  • Explicitly start a particular Service or Activity using its class name;
  • Start an Activity or Service to perform an action with (or on) a particular piece of data;
    • When Intent is used to implicitly request an action be performed on a piece of data, the action does not need to be performed by an Activity within the calling application.
  • Broadcast that an event has occurred.
    • Applications can register Broadcast Receivers to listen for, and react to, these Broadcast Intents.
    • Android broadcasts Intents to announce system events, such as changes in Internet connectivity or battery charge levels.


Using Intents to Launch Activities

The most common use of Intents is to bind your application components and communicate between them. Intents are used to start Activities, allowing you to create a workflow of different screens.


To create and display an Activity, call startActivity, passing in an Intent, as follows:

startActivity(myIntent);


  • The startActivity method finds and starts the single Activity that best matches your Intent.
  • You can construct the Intent to explicitly specify the Activity class to open, or to include an action that the target Activity must be able to perform. In the latter case, the run time will choose an Activity dynamically using a process known as intent resolution.
  • When you use startActivity, your application won't receive any notification when the newly launched Activity finishes.


Explicitly Starting New Activities

To select a specific Activity class to start, create a new Intent, specifying the current Activity's Context and the class of the Activity to launch. Pass this Intent into startActivity:

Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);startActivity(intent);
  • Calling finish on the new Activity, or pressing the hardware back button, closes it and removes it from the stack.
  • Or you can continue to navigate to other Activities by calling startActivity.
  • Each time you call startActivity, a new Activity will be added to the stack; pressing back (or calling finish) will remove each of these Activities, in turn.


Implicit Intents and Late Runtime Binding

You can ask the system to start an Activity to perform an action without knowing which application, or Activity, that is implicit Intent.

For example, to let users make calls from your application, you could use an implicit Intent that requests the action (dialing) be performed on a phone number

if (somethingWeird && itDontLookGood) {Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));startActivity(intent);}


........


Introducing Linkify


Native Linkify Link Types

...

Creating Custom Link Strings

...

Using the Match Filter

...

Using the Transform Filter

...


Using Intents to Broadcast Events

As a system-level message-passing mechanism, Intents are capable of sending structured messages across process boundaries. As a result, you can implement Broadcast Receivers to listen for, and respond to, these Broadcast Intents within your applications.


Broadcasting Events with Intents

public static final String NEW_LIFEFORM_DETECTED = "com.paad.action.NEW_LIFEFORM";Intent intent = new Intent(LifeformDetectedReceiver.NEW_LIFEFORM);intent.putExtra(LifeformDetectedReceiver.EXTRA_LIFEFORM_NAME, detectedLifeform);intent.putExtra(LifeformDetectedReceiver.EXTRA_LONGITUDE, currentLongitude);intent.putExtra(LifeformDetectedReceiver.EXTRA_LATITUDE, currentLatitude);sendBroadcast(intent);


  • The Intent action string is used to identify the event, it should be a unique string.
  • You can include extras to pass additional primitive values into an event handler.


Listening for Broadcasts with Broadcast Receivers

For a Receiver to receive broadcasts, it must be registered, either in code or within the application manifest — the latter case is referred to as a manifest Receiver. In either case, use an Intent Filter to specify which Intent actions and data your Receiver is listening for.


To create a new Broadcast Receiver, extend the BroadcastReceiver class and override the onReceive event handler:

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {//TODO: React to the Intent received.}}


Broadcasting Ordered Intents

...


Broadcasting Sticky Intents

...


Introducing the Local Broadcast Manager

  • The Local Broadcast Manager was introduced to simplify the process of registering for, and sending, Broadcast Intents between components within your application.
  • It is more efficient. The Intent you broadcast cannot be received by any components outside your application, so more secure.

Introducing Pending Intents

The PendingIntent class provides a mechanism for creating Intents that can be fired on your application's behalf by another application at a later time.


CREATING INTENT FILTERS AND BROADCAST RECEIVERS

  • In the case of Activities and Services, an Intent is a request for an action to be performed on a set of data.
  • An Intent Filter is a declaration that a particular application component is capable of performing an action on a type of data.
  • Intent Filters are also used to specify the actions a Broadcast Receiver is interested in receiving.


Using Intent Filters to Service Implicit Intents

  • Using Intent Filters, application components can declare the actions and data they support.
  • So that Android knows which application (and component) to use to service a request for an action to be performed on a set of data by an Intent.
  • To register an Activity or Service as a potential Intent handler, add an intent-filter tag to its manifest node.


How Android Resolves Intent Filters

The process of deciding which Activity to start when an implicit Intent is passed in to start Activity is called intent resolution. The aim of intent resolution is to fi nd the best Intent Filter match possible by means of the following process:


Finding and Using Intents Received Within an Activity

When an application component is started through an implicit Intent, it needs to find the action it's to perform and the data to perform it on.


Passing on Responsibility

You can use startNextMatchingActivity to pass responsibility for action handling to the next best Activity.


Selecting a Contact Example

...


Using Intent Filters for Plug-Ins and Extensibility

Applications can also query to find which actions are available to be performed on a particular piece of data.


Android provides a plug-in model that lets your applications take advantage of functionality, provided anonymously from your own or third-party application components you haven't yet conceived of, without your having to modify or recompile your projects.


Supplying Anonymous Actions to Applications

To use this mechanism to make your Activity's actions available anonymously for existing applications, publish them using intent-filter tags within their manifest nodes, as described earlier.

Question: is the laterly developed Activity within that existing application or not?


Discovering New Actions from Third-Party Intent Receivers

Using the Package Manager, you can create an Intent that specifies a type of data and a category of action, and have the system return a list of Activities capable of performing an action on that data.


Incorporating Anonymous Actions as Menu Items

The most common way to incorporate actions from third-party applications is to include them within your Menu Items or Action Bar Actions.

The addIntentOptionsmethod, available from the Menu class, lets you specify an Intent that describes the data acted upon within your Activity, as described previously; however, rather than simply returning a list of possible Receivers, a new Menu Item will be created for each, with the text populated from the matching Intent Filters' labels.


Listening for Native Broadcast Intents

Many of the system Services broadcast Intents to signal changes. You can use these messages to add functionality to your own projects based on system events, such as time-zone changes, data-connection status, incoming SMS messages, or phone calls.


Monitoring Device State Changes Using Broadcast Intents

...


Managing Manifest Receivers at Run Time

  • Using the Package Manager, you can enable and disable any of your application's manifest Receivers at run time using thesetComponentEnabledSetting method. You can use this technique to enable or disable any application component (including Activities and Services), but it is particularly useful for manifest Receivers.
  • To minimize the footprint of your application, it's good practice to disable manifest Receivers that listen for common system events (such as connectivity changes) when your application doesn't need to respond to those events.
  • This technique also enables you to schedule an action based on a system event — such as downloading a large file when the device is connected to Wi-Fi — without gaining the overhead of having the application launch every time a connectivity change is broadcast.





0 0