Start from scratch-go deep into Android (practice-let's start writing code-Beginner's Guide-1. Hello, world)

Source: Internet
Author: User
Tags android sdk manager
Chapter 2 Hello, world

As a developer, the first impression of a platform must be "Hello, world ". Writing "Hello, world" on Android is very simple. Because we use eclipise IDE, it provides a powerful plug-in such as ADT, which makes it easier to create and manage a project, it can greatly shorten our time. Before you start, make sure that you have installed the SDK and ADT plug-in. This chapter describes the following parts:

1. Install a platform (System Version)

2. Create an android Virtual Machine (AVD)

3. Create a project

4. Build a user interface

5. ExecuteCode

6. Upgrade the interface to an XML Layout

7. debug your project

1.1 install a platform (System Version)

To execute the Hello world applicationProgram, You need to install at least one Android platform version in your SDK environment. If you have already installed the platform, you can skip this step. Please download the most practical platform version based on your actual situation, I downloaded the platform version 1.6 ---- 2.1 ---- 2.2 --- 2.3 ---- 3.0. Download the version based on your actual situation. If you have not downloaded a platform version, perform the following steps on eclpise:

1. In Android SDK manager, selectAvailable packages

2. In the right pane, expandAndroid RepositoryThe list shows some available installation components.

3. select at least one platform for installation and clickInstall selected

1.2 create an android Virtual Machine (AVD)

We have already talked about how to use and manage AVD in the first article. In this chapter, we will execute our applications in the android simulator. Therefore, you must create an AVD before starting a simulator. The procedure is as follows:

1. In eclipse, selectWindow> AVD Manager

2. SelectVirtual Devices

3. ClickNew...

Then comeCreate new AVDDialog Box

4. Enter the Virtual Machine name. All my virtual machines use the system version name, for example, "avd2.2.

5. Select a target (Android SDK version 2.3.3 ). In this chapter, the following fields are omitted for simplicity.

6. Click Create AVD.

1.3 create a new Android Project

To create a new Android project, follow these steps:

1. In eclipse, select File> New> project...

If your ADT plug-in is correctly installed, the 1-1 interface is displayed.

 

Figure 1-1Create an android project in eclipse

2. Select "android project" and clickNext
3. Follow these steps to enter project details, as shown in 1-2:

◆ Project name: helloandroid

◆ Build target: select the corresponding application based on the system version created by your Virtual Machine
Name: Hello, Android

◆ Package name: COM. example. helloandroid (package name)

◆ Create activity: helloandroid (main activity name)

 

Figure 1-2Fill in the relevant details in eclipse to create an android Project

Here we will talk about the following min SDK version field: When we select 2.1 for build target (the corresponding API level is 7), we should enter a version 7 or earlier, for example, 3 or 4. Remember not to enter a value greater than 7. Otherwise, there will be some errors and risks. After the project has been created, open the helloandroid. Java file in the package explorer panel on the left of Eclipse, which is located in helloandroid> SRC
> Com. example. helloandroid. The Code is as follows:

Package com. example. helloandroid; import Android. App. Activity; import Android. OS. Bundle; publicclasshelloandroidextendsactivity {/** Called when the activity is first created.*/@ Override publicvoid oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. Main );}}

 

 

Code List 1-1

Note that helloandroid inherits from the activity class. An activity is a single application entity used to execute actions. An application may consist of multiple activityies, but at a certain moment there is only one acities interacting with the user. After your activity is started, the android system will call the oncreate () method. You should perform initialization and UI settings here. An activity can be correctly executed without a user interface. However, we usually need to add a basic user interface to display some things. Let's modify some code!

1.4 build a user interface

The Code is also improved in the helloandroid class. The bold text below is newly added.

Package com. example. helloandroid; import Android. App. Activity; import Android. OS. Bundle; import Android. widget. textview;  Public   Class  Helloandroid extends activity {  /*  * Called when the activity is first created.  */  @ Override  Public   Void  Oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); textview TV = New Textview (This  ); TV. settext (  "  Hello, Android  "  ); Setcontentview (TV );}} 

 

Code List 1-2

An android user interface consists of the object hierarchy of views. A view is a printable object and serves as a UI layout element, such as a button, image, or textview (Text tag ). Each UI element is a view, which inherits directly or indirectly from the View class. Here we create a textview object and need to upload a context instance object. Context is used to process system-related operations, such as solving resource calls and obtaining database access interfaces and preferences. The activity class inherits from the context, so you can directly upload "this" here ". Next, we need to use settext () to set the text content. Finally, we need to add textview to our current activity interface through setcontextview. If you do not call setcontextview (), the system will not display this textview, but a blank screen with full background black.

Okay, the "Hello, Android" project code has been written, and we need to execute it.

1.5 run the application

Since there is a plug-in eclpise, it is easy to execute and there are many methods. Here we can right-click the project and choose run as> anroid Application

The Eclipse plug-in automatically creates a new running configuration file for your project and starts the android simulator. According to your environment, it may take several minutes for the android simulator to fully start. Please be patient. After the agent is started, the Eclipse plug-in installs the application and starts the default activity. The display effect is 1-3:

 

Figure 1-3Start hello, Android

The "Hello, Android" displayed in the gray bar of the application is actually the title of the application. When a project is created, the Eclipse plug-in automatically creates Res/values/strings. xml. Then androidmanifest. xml references the title field in strings. xml. The text under the title is the textview we wrote in the code. Although "Hello World" has been written, you can continue to read other valuable information in the project.

1.6 upgrade the interface into an XML Layout

In the "Hello, world" example, we use the code layout. If you are an experienced UI programmer, you may be very vulnerable to this practice: small changes in the layout may lead to a large number of code changes, it is easy to forget other views related to it, which will lead to layout errors and waste a lot of time debugging. Therefore, Android provides an XML-based layout file instead of the code writing Layout mode. Let's take an example below. We don't use the code layout as a textview, but use the following XML file instead of the Code layout as the result of the above "Code List 1-2:

<? XML version = " 1.0  " Encoding = "  UTF-8  " ?> <Textview xmlns: Android = "  Http://schemas.android.com/apk/res/android  "  Android: ID = "  @ + ID/textview  "  Android: layout_width = "  Fill_parent "  Android: layout_height = "  Fill_parent  "  Android: Text = "  @ String/Hello  " />

 

This is a simple Android XML layout file structure: it is a tree node, where each node is a view. All the elements we use are inherited from the View class. textview is a view that android has written. Of course, we can also customize the view in the code. This structure can easily create a user interface, which uses a simpler structure and syntax than code layout. In the preceding XML layout file, there is only one textview node, but several attributes are used here. As shown in Table 1-1:

Attribute

Description

Xmlns: Android

This is an XML namespace declaration that tells android that you will reference the common attributes defined in the android namespace. This attribute is required for the outermost tag of each android layout file.

Android: ID

This attribute specifies the unique identifier of a textview element. You can use the assigned ID fromSource code.

Android: layout_width

This attribute defines the width required for this view. "fill_paren" indicates that the full width of the parent node is occupied. The parent node is the screen.

Android: layout_height

Similar to width, indicating height

Android: Text

Set the text to be displayed in textview. In this example, we use a hard-coded string value instead of a referenced string resource. Of course, a better way is to reference the hello string defined in the Res/strings. xml file. Because it is in line with internationalization. Hard encoding is used for the sake of simplicity.

Table 1-1Node attributes in XML

These XML layout files are stored in the Res/layout/directory of your project ." Res stands for resources. This directory contains all non-code resources, in addition to layout folders, images, sounds, and localized strings.

The default Layout mode for Android is vertical layout. In the multi-screen multi-resolution chapter, I have already introduced the layout. here our XML is placed under layout, layout is the default vertical layout. If your phone is placed horizontally, Android will display the horizontal layout. Because we didn't put the layout file under Layout-land, therefore, it will be stretched directly under the vertical layout. Of course, this is just a small tip. These details must be taken into consideration when a project is created. For the sake of simplicity, let's stretch it. The Eclipse plug-in creates a main. xml layout file under Res/layout/when creating a project. The main. xml layout file is not used in "Code List 1-2.

Now let's modify "Code List 1-2", as shown in "Code List 1-3 ".

Package com. example. helloandroid; import Android. App. Activity; import Android. OS. Bundle;Public ClassHelloandroid extends activity {/** Called when the activity is first created.*/@ OverridePublic VoidOncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. Main );}}

 

Code List 1-3

We gave up. In "Code List 1-2", the code generated view method is switched to the "Code List 1-3" XML layout file. You will find that only one line is done, next let's take a look at the R class (commonly known as the r file ). Find our R. Java in the project GEN/in eclipse. The Code is as follows:

Package com. example. helloandroid;  Public Final Class  R {  Public   Static Final Class  ATTR {}  Public   Static Final Class  Drawable {  Public   Static Final Int Icon = 0x7f020000  ;}  Public   Static Final Class  Id {  Public   Static Final Int Textview = 0x7f050000  ;}  Public   Static Final Class  Layout { Public   Static Final Int Main = 0x7f030000  ;}  Public   Static Final Class   String  {  Public   Static Final Int App_name = 0x7f040001  ; Public   Static Final Int Hello = 0x7f040000  ;}} 

 

Code List 1-4

The r file in a project is used to save reference of all resources. If you want to reference the resource file in the Code, the R file is used to reference their ID. This file does not need to be modified. When you copy resources to the project, it will automatically generate the resource reference ID.

1.7 debug your project

Of course, debugging is essential. The Android plug-in eclipse is well integrated with the eclipse debugger. To prove this, let's look at "Code List 1-5"

Package com. example. helloandroid; import Android. App. Activity; import Android. OS. Bundle;Public ClassHelloandroid extends activity {/** Called when the activity is first created.*/@ OverridePublic VoidOncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); object o=Null; O. tostring (); setcontentview (R. layout. Main );}}

 

Code List 1-5

Introduce a null pointer exception in your code, and then you will see the effects of 1-4 in the simulator.

 

Figure 1-4Null Pointer exception in Android devices

We can set a breakpoint in the object o = NULL; line (double-click the code line next to it), right-click and choose run> debug as> Android Application. Then run the debug mode and stop at the breakpoint. Then go to the debugging page. You can hover your mouse over or observe the variable values in the upper right corner, as shown in figure 1-5:

Figure 1-5Android debugging Interface

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.