2013-7-11

Create a Project with Command Line Tools

Change directories into the Android SDKtools/ path.

android list targets

This prints a list of the available Android platforms that you’ve downloaded for your SDK. Find the platform against which you want to compile your app. Make a note of the target id. We recommend that you select the highest version possible. You can still build your app to support older versions, but setting the build target to the latest version allows you to optimize your app for the latest devices.

If you don't see any targets listed, you need to install some using the Android SDK Manager tool. See Adding Platforms and Packages.

android create project --target  --name MyFirstApp \

--path /MyFirstApp --activity MainActivity \

--package com.example.myfirstapp

Replace  with an id from the list of targets (from the previous step) and replace  with the location in which you want to save your Android projects.

The AndroidManifest.xml File

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. Among other things, the manifest does the following:

· It names the Java package for the application. The package name serves as a unique identifier for the application.

· It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.

· It determines which processes will host application components.

· It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.

· It also declares the permissions that others are required to have in order to interact with the application's components.

· It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.

· It declares the minimum level of the Android API that the application requires.

· It lists the libraries that the application must be linked against.

Building a Simple User Interface

The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets such as buttons or text fields and ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.

Layouts

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:

· Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.

· Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.

Load the XML Resource

When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:

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

Attributes

Every View and ViewGroup object supports their own variety of XML attributes. 

Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the Viewclass)。

The syntax for an ID, inside an XML tag is:

android:id="@+id/my_button"

The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:

android:id="@android:id/empty"

With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.

In order to create views and reference them from the application, a common pattern is to:

Define a view/widget in the layout file and assign it a unique ID:

 android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/my_button_text"/>

Then create an instance of the view object and capture it from the layout (typically in the onCreate()method):

Button myButton = (Button) findViewById(R.id.my_button);

Layout Position

The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and topcoordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.

methods getLeft() getTop() getRight() getBottom()

Size, Padding and Margins

The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.

The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent. The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().

The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight() .

To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. 

padding是控件的内容相对控件的边缘的边距.
margin是控件边缘相对父控件,或者其他控件的边距.

Common Layouts

a wide view hierarchy is better than a deep view hierarchy.

Linear Layout:A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.

Relative Layout:Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent).

Web View:Displays web pages.

Building Layouts with an Adapter

When the content for your layout is dynamic or not pre-determined, you can use a layout that subclasses AdapterView to populate the layout with views at runtime. A subclass of the AdapterView class uses an Adapterto bind data to its layout. The Adapter behaves as a middle-man between the data source and the AdapterView layoutthe Adapter retreives the data (from a source such as an array or a database query) and converts each entry into a view that can be added into the AdapterView layout.

Common layouts backed by an adapter include:

List View、Grid View

Filling an adapter view with data

You can populate an AdapterView such as ListView or GridView by binding the AdapterView instance to anAdapter, which retrieves data from an external source and creates a View that represents each data entry.

Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView. The two most common adapters are:

ArrayAdapter

Use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling toString() on each item and placing the contents in a TextView.

For example, if you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array:

ArrayAdapter adapter = new ArrayAdapter<String>(this, 
        android.R.layout.simple_list_item_1, myStringArray);

The arguments for this constructor are:

Your app Context

The layout that contains a TextView for each string in the array

The string array

Then simply call setAdapter() on your ListView:

ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);

To customize the appearance of each item you can override the toString() method for the objects in your array. Or, to create a view for each item that's something other than a TextView (for example, if you want anImageView for each array item), extend the ArrayAdapter class and override getView() to return the type of view you want for each item.

SimpleCursorAdapter

Use this adapter when your data comes from a Cursor. When using SimpleCursorAdapter, you must specify a layout to use for each row in the Cursor and which columns in the Cursor should be inserted into which views of the layout. For example, if you want to create a list of people's names and phone numbers, you can perform a query that returns a Cursor containing a row for each person and columns for the names and numbers. You then create a string array specifying which columns from the Cursor you want in the layout for each result and an integer array specifying the corresponding views that each column should be placed:

String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, 
                        ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};

When you instantiate the SimpleCursorAdapter, pass the layout to use for each result, the Cursor containing the results, and these two arrays:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);

The SimpleCursorAdapter then creates a view for each row in the Cursor using the provided layout by inserting each fromColumns item into the corresponding toViews view.

If, during the course of your application's life, you change the underlying data that is read by your adapter, you should call notify DataSetChanged(). This will notify the attached view that the data has been changed and it should refresh itself.

Handling click events

You can respond to click events on each item in an AdapterView by implementing theAdapterView.OnItemClickListener interface. For example:

// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // Do something in response to the click
    }
};
listView.setOnItemClickListener(mMessageClickedHandler); 

Resource Types

http://developer.android.com/guide/topics/resources/available-resources.html#dimension

Animation Resources

Define pre-determined animations.
Tween animations are saved in res/anim/ and accessed from the R.anim class.
Frame animations are saved in res/drawable/ and accessed from the R.drawable class.

Color State List Resource

Define a color resources that changes based on the View state.
Saved in res/color/ and accessed from the R.color class.

Drawable Resources

Define various graphics with bitmaps or XML.
Saved in res/drawable/ and accessed from the R.drawable class.

Layout Resource

Define the layout for your application UI.
Saved in res/layout/ and accessed from the R.layout class.

Menu Resource

Define the contents of your application menus.
Saved in res/menu/ and accessed from the R.menu class.

String Resources

Define strings, string arrays, and plurals (and include string formatting and styling).
Saved in res/values/ and accessed from the R.string, R.array, and R.plurals classes.

Style Resource

Define the look and format for UI elements.
Saved in res/values/ and accessed from the R.style class.

More Resource Types

Define values such as booleans, integers, dimensions, colors, and other arrays.
Saved in res/values/ but each accessed from unique R sub-classes (such as R.bool, R.integer, R.dimen, etc.).

About resource objects

A resource object is simply a unique integer name that's associated with an app resource, such as a bitmap, layout file, or string.

Every resource has a corresponding resource object defined in your project's gen/R.java file. You can use the object names in the R class to refer to your resources, such as when you need to specify a string value for the android:hint attribute. You can also create arbitrary resource IDs that you associate with a view using the android:id attribute, which allows you to reference that view from other code.

The SDK tools generate the R.javaeach time you compile your app. You should never modify this file by hand.

Add a Text Field

   android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />

The at sign (@) is required when you're referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (edit_message).

The plus sign (+) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's gen/R.java file that refers to the EditText element. Once the resource ID is declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts.

android:hint

This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, youll see a compiler error at first. You'll fix this in the next section by defining the string.

Note: This string resource has the same name as the element ID: edit_message. However, references to resources are always scoped by the resource type (such as id or string), so using the same name does not cause collisions.

Add String Resources

When you need to add text in the user interface, you should always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.

By default, your Android project includes a string resource file at res/values/strings.xml. Add a new string named "edit_message" and set the value to "Enter a message." (You can delete the "hello_world" string.)

The result for strings.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>

     name="app_name">My First App
     name="edit_message">Enter a message
     name="title_activity_main">MainActivity


更多相关文章

  1. Android UI控件之ToggleButton、Switch
  2. Android - GridView,自定义开关控件,状态选择器selector,自定义对话
  3. View控件中android:drawablePadding不起作用的原因探究
  4. Android控件编辑时键盘弹起与关闭处理

随机推荐

  1. Android转场动画和共享元素动画兼容5.0以
  2. Android中基于心知天气API获取天气信息
  3. Android(4.2) Sensors 学习——G-sensor,
  4. Android中我为什么发不了邮件--Android邮
  5. Android(安卓)TV 焦点移动飞框的实现
  6. android 新浪微博客户端的表情功能的实现
  7. Android(安卓)Studio 基础 之 一键快速实
  8. Android心得3--拨号器
  9. Android练习项目 Mp3播放器实现(一)
  10. Android(安卓)HAL实现的三种方式(1) - 基