Android cainiao study Note 5 ---- first android program, android5 ----

Source: Internet
Author: User

Android cainiao study Note 5 ---- first android program, android5 ----

Program function: click a button and a prompt is displayed.

Step 1: create an android application project in eclipse. If you do not select create activity during creation, an empty android project is created.

 

In this case, src and res/layout are empty.

Step 2: Create an Activity in src that inherits from android. app. Activity. Click finish to generate the Code as follows:

 1 package cn.csc.hello_world; 2  3   4  5 import android.app.Activity; 6  7   8  9 public class FirstActivity extends Activity {10 11  12 13 }

 

 

Press shift + alt + S and select Override/Implement Methods from the pop-up menu:

 

Check onCreate (Bundle) and click OK to implement the onCreate (Bundle) method of the Activity. The automatically generated code is as follows:

1     @Override2 3       protected void onCreate(Bundle savedInstanceState) {4 5            // TODO Auto-generated method stub6 7            super.onCreate(savedInstanceState);8 9       }

 

Step 3: Create a layout file with only one button in the res/layout directory

Right-click layout --> new --> Android Xml File:

The file name is first_layout.

Select LinearLayout as the root node.

Click Finish.

 

The automatically generated code in first_layout.xml is as follows:

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 3 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 4 5 android: layout_width = "match_parent" width: Fill parent node 6 7 android: layout_height = "match_parent" height: fill in parent node 8 9 android: orientation = "vertical"> sub-node arrangement direction: vertical arrangement of 10 11 </LinearLayout>

 

Add a Button subnode in LinearLayout, input butt, and then alt +/to automatically complete the button subnode. To add attributes, you can also enter several initials, and then alt +/complete

1 <Button 2 3 android: id = "@ + id/btn" add an id. If you reference this button later, R. id. btn 4 5 android: layout_width = "wrap_content" Package content can be 6 7 android: layout_height = "wrap_content" Package content can be 8 9 android: text = "I'm a button" The text displayed on the button is 10 11/>

 

Here, the text property is directly set as a string, hard encoding is not good, the mouse points to "I'm a button", so that the cursor stays at any position of the string, press ctrl + 1 (number 1). In the pop-up menu, select Extract Android String:

 

Replace by R. string. btnText, and then click OK. The text attribute changes to android: text = "@ string/btnText". To reference this string later, you can use R. string. btnText.

Step 4: Set the layout file for the newly created FirstActivity to first_layout.xml

In the onCreate () method of FirstActivity, add the following:

1 protected void onCreate(Bundle savedInstanceState) {2 3            // TODO Auto-generated method stub4 5            super.onCreate(savedInstanceState);6 7            setContentView(R.layout.first_layout);8 9 }

 

In this case, the first_layout and setContentView () statements cannot be found.

Observe the FirstActivity code and you will find that an additional sentence is imported to android. R;

Delete it or report an error, prompting that R cannot be found.

(Note: If you press Ctrl + 1 to fix the code, import com. example. hello_world.R;

Although no error will be reported, if you do not specify the full package name. Class Name When registering the Activity later, the program cannot run. If you do not specify the full package name, the system prompts that the required Activity cannot be found. For the sake of simplicity, you can perform the following operations to modify the package attribute. Of course, you can also do not modify the attribute. When registering each component, you must add the package name)

Find Android Manifest. xml file. The package attribute in the root node manifest is not the FirstActivity we set. java package name, but the default package name when creating the project, and the package cn. csc. hello_world is created later. As a result, R. java and FirstActivity. java are not in the same package and therefore cannot be accessed directly.

1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"2 3     package="com.example.hello_world"4 5     android:versionCode="1"6 7 android:versionName="1.0" >

 

Change the package property value to the package name of FirstActivity: package = "cn. csc. hello_world ".

In this way, R. java and FirstActivity. java are in the same package and can be accessed directly.

Then return to the FirstActivity code and find that no error is reported.

Step 5: Find the Add button and set it to click the RESPONSE event

The onCreate () code is modified as follows:

 1 protected void onCreate(Bundle savedInstanceState) { 2  3            // TODO Auto-generated method stub 4  5            super.onCreate(savedInstanceState); 6  7            setContentView(R.layout.first_layout); 8  9            Button btn = (Button) findViewById(R.id.btn);10 11            btn.setOnClickListener(new OnClickListener() {12 13                      @Override14 15                      public void onClick(View arg0) {16 17               Toast.makeText(FirstActivity.this, "I was clicked", Toast.LENGTH_SHORT).show();18 19                      }20 21               });22 23 }

 

FindViewById () locate the desired View based on the Id

Btn. setOnClickListener () Setting click event listening. Here anonymous internal class implementation is selected.

Toast. makeText (). show (); a prompt is displayed.

Step 6: register the FirstActivity to be used

After Step 5 is completed, if the program is run, no effect will be found, because the Activity to be used is not registered in Android Manifest. xml. Therefore, FirstActivity will not be used, and its onCreate () method will not be called.

The FirstActivity registration method is as follows:

Add an activity subnode to the application node:

 1 <activity  android:name=".FirstActivity"      android:label="Hello world" > 2  3             <intent-filter > 4  5                 <action android:name="android.intent.action.MAIN"/> 6  7                 <category android:name="android.intent.category.LAUNCHER"/> 8  9             </intent-filter>10 11 </activity>

 

The name attribute must be set to specify the Activity class to be registered. firstActivity Concatenates the package attribute in the manifest node into a complete class name. You can also write a complete class name, such as cn. csc. hello_world.FirstActivity

Label attribute to set the title of the application. If not set, the title is the project name.

Intent-filter sets the intention to start the activity. Here, this activity is set to start the activity.

Now, the program can run smoothly.

 

If you do not want to display the application title bar, you can add requestWindowFeature (Window. FEATURE_NO_TITLE) in the onCreate () method );

However, you must add the code before setContentView (). Otherwise, an error is returned.

 

Summary:

If this error message does not result in R, You can first check whether the package names set before and after are inconsistent. As a result, R. java and the code you have written are not in the same package.

Manifest. the package attribute in xml is set in the new project. It is used to uniquely identify the current application on the mobile phone. You can create a new package name for the source code package. when registering each component, you should use the complete class qualified name, that is, the package name. class Name. Otherwise, the package attribute and the name attribute of the registered component are spliced into an incorrect class limitation name, And the definition class of the component cannot be found.

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.