From ae47d9d4fe28b9c67e9669ecd2f534e27a921d30 Mon Sep 17 00:00:00 2001 From: Mark Lu Date: Fri, 15 Jul 2016 13:36:55 -0700 Subject: [PATCH] docs: updates to Buildilng Your First App doc This commit includes the following updates: - replaces Basic activity with Empty activity - uses default values wherever possible - removes instructions for floating button - removes SDK instructions. Users must use Android Studio - updates the SDK version to API 15 - combines some instructions that were too text heavy Bug: 29766869 Bug: 29768686 Bug: 19154557 Change-Id: Id819cb2dde74b68b5145dfefe7a8502892bb377a (cherry picked from commit 08d1bff71f19e5567b8f545314fd84701e9b2cec) --- docs/html/training/basics/firstapp/building-ui.jd | 188 +++---- .../training/basics/firstapp/creating-project.jd | 102 ++-- docs/html/training/basics/firstapp/index.jd | 29 +- docs/html/training/basics/firstapp/running-app.jd | 102 ++-- .../training/basics/firstapp/starting-activity.jd | 577 ++++++--------------- 5 files changed, 296 insertions(+), 702 deletions(-) diff --git a/docs/html/training/basics/firstapp/building-ui.jd b/docs/html/training/basics/firstapp/building-ui.jd index 275500c88141..a680c733f99e 100644 --- a/docs/html/training/basics/firstapp/building-ui.jd +++ b/docs/html/training/basics/firstapp/building-ui.jd @@ -71,38 +71,31 @@ android.view.View} objects.

Create a Linear Layout

    -
  1. In Android Studio, from the res/layout directory, open the {@code content_my.xml} -file. -

    The BlankActivity template you chose when you created this project includes the -content_my.xml file with a {@link android.widget.RelativeLayout} root view and a -{@link android.widget.TextView} child view.

    -
  2. -
  3. In the Preview pane, click the Hide icon to close the Preview pane. -

    In Android Studio, when you open a layout file, you’re first shown - the Preview pane. Clicking elements in this pane opens the WYSIWYG tools in the Design pane. For - this lesson, you’re going to work directly with the XML.

  4. -
  5. Delete the {@link android.widget.TextView <TextView>} element.
  6. -
  7. Change the {@link android.widget.RelativeLayout <RelativeLayout>} element to -{@link android.widget.LinearLayout <LinearLayout>}.
  8. -
  9. Add the -{@code android:orientation} attribute and set it to "horizontal".
  10. -
  11. Remove the {@code android:padding} attributes and the {@code tools:context} attribute. -
- -

The result looks like this:

- -
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
+  
  • From the res/layout/ directory, open the + activity_main.xml file. +

    This XML file defines the layout of your activity. It contains the + default "Hello World" text view.

    +
  • +
  • When you open a layout file, you’re first shown the design editor in the + Layout Editor. For this lesson, + you work directly with the XML, so click the Text tab to switch to + the text editor. +
  • +
  • Replace the contents of the file with the following XML: +
    <?xml version="1.0" encoding="utf-8"?>
    +<LinearLayout
    +    xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
    -    android:orientation="horizontal"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
    -    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    -    tools:showIn="@layout/activity_my">
    +    android:orientation="horizontal">
    +</LinearLayout>
     
    +
  • + + +

    {@link android.widget.LinearLayout} is a view group (a subclass of {@link android.view.ViewGroup}) that lays out child views in either a vertical or horizontal orientation, as specified by the Layout guide.

    Add a Text Field

    -

    As with every {@link android.view.View} object, you must define certain XML attributes to specify -the {@link android.widget.EditText} object's properties.

    - -
      -
    1. In the content_my.xml file, within the -{@link android.widget.LinearLayout <LinearLayout>} element, define an -{@link android.widget.EditText <EditText>} element with the id attribute -set to @+id/edit_message.
    2. -
    3. Define the layout_width and layout_height attributes as -wrap_content.
    4. -
    5. Define a hint attribute as a string object named edit_message.
    6. -
    - -

    The {@link android.widget.EditText <EditText>} element should read as follows:

    +

    In the activity_main.xml file, within the +{@link android.widget.LinearLayout <LinearLayout>} element, add the following +{@link android.widget.EditText <EditText>} element:

    -
    -<EditText android:id="@+id/edit_message"
    -    android:layout_width="wrap_content"
    -    android:layout_height="wrap_content"
    -    android:hint="@string/edit_message" />
    +
    <LinearLayout
    +    xmlns:android="http://schemas.android.com/apk/res/android"
    +    xmlns:tools="http://schemas.android.com/tools"
    +    android:layout_width="match_parent"
    +    android:layout_height="match_parent"
    +    android:orientation="horizontal">
    +    <EditText android:id="@+id/edit_message"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:hint="@string/edit_message" />
    +</LinearLayout>
     
    -

    Here are the {@link android.widget.EditText <EditText>} attributes you added:

    +

    Here is a description of the attributes in the + {@link android.widget.EditText <EditText>} you added:

    {@code android:id}
    @@ -222,29 +211,20 @@ the same name does not cause collisions.

    Add String Resources

    By default, your Android project includes a string resource file at -res/values/strings.xml. Here, you'll add a new string named -"edit_message" and set the value to "Enter a message."

    +res/values/strings.xml. Here, you'll add two new strings.

      -
    1. In Android Studio, from the res/values directory, open strings.xml.
    2. -
    3. Add a line for a string named "edit_message" with the value, "Enter a message". -
    4. -
    5. Add a line for a string named "button_send" with the value, "Send". -

      You'll create the button that uses this string in the next section.

      -
    6. -
    - -

    The result for strings.xml looks like this:

    - -
    -<?xml version="1.0" encoding="utf-8"?>
    +
  • From the res/values/ directory, open strings.xml.
  • +
  • Add two strings so that your file looks like this: +
    <?xml version="1.0" encoding="utf-8"?>
     <resources>
         <string name="app_name">My First App</string>
    -    <string name="edit_message">Enter a message</string>
    -    <string name="button_send">Send</string>
    -    <string name="action_settings">Settings</string>
    +    <string name="edit_message">Enter a message</string>
    +    <string name="button_send">Send</string>
     </resources>
     
    +
  • +

    For text in the user interface, always specify each string as a resource. String resources allow you to manage all UI text in a single location, @@ -260,40 +240,22 @@ class.

    Add a Button

    -
      -
    1. In Android Studio, from the res/layout directory, edit the content_my.xml -file.
    2. -
    3. Within the -{@link android.widget.LinearLayout <LinearLayout>} element, define a -{@link android.widget.Button <Button>} element immediately following the -{@link android.widget.EditText <EditText>} element.
    4. -
    5. Set the button's width and height attributes to "wrap_content" so -the button is only as big as necessary to fit the button's text label.
    6. -
    7. Define the button's text label with the {@code -android:text} attribute; set its value to the button_send string -resource you defined in the previous section.
    8. -
    - -

    Your {@link android.widget.LinearLayout <LinearLayout>} should look like this:

    - -
    -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -    xmlns:app="http://schemas.android.com/apk/res-auto"
    +

    Go back to the activity_main.xml file and add a button after the + {@link android.widget.EditText <EditText>}. Your file should look like this:

    +
    <LinearLayout
    +    xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:orientation="horizontal"
         android:layout_width="match_parent"
    -    android:layout_height="match_parent"
    -    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    -    tools:showIn="@layout/activity_my">
    +    android:layout_height="match_parent">
             <EditText android:id="@+id/edit_message"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:hint="@string/edit_message" />
    -        <Button
    +        <Button
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
    -          android:text="@string/button_send" />
    +          android:text="@string/button_send" />
     </LinearLayout>
     
    @@ -302,7 +264,7 @@ resource you defined in the previous section. attribute, because it won't be referenced from the activity code.

    The layout is currently designed so that both the {@link android.widget.EditText} and {@link -android.widget.Button} widgets are only as big as necessary to fit their content, as Figure 2 shows. +android.widget.Button} widgets are only as big as necessary to fit their content, as figure 2 shows.

    @@ -334,53 +296,36 @@ given the space they require.

    Make the Input Box Fill in the Screen Width

    -

    To fill the remaining space in your layout with the {@link android.widget.EditText} element, do -the following:

    - -
      -
    1. In the content_my.xml file, assign the -{@link android.widget.EditText <EditText>} element's layout_weight attribute a value -of 1.
    2. -
    3. Also, assign {@link android.widget.EditText <EditText>} element's layout_width -attribute a value of 0dp. +

      In activity_main.xml, modify the + {@link android.widget.EditText <EditText>} so that the attributes look like + this:

      -<EditText
      -    android:layout_weight="1"
      -    android:layout_width="0dp"
      -    ... />
      +<EditText android:id="@+id/edit_message"
      +    android:layout_weight="1"
      +    android:layout_width="0dp"
      +    android:layout_height="wrap_content"
      +    android:hint="@string/edit_message" />
       
      -

      To improve the layout efficiency when you specify the weight, you should change the -width of the {@link android.widget.EditText} to be -zero (0dp). Setting the width to zero improves layout performance because using +

      Setting the width to zero (0dp) improves layout performance because using "wrap_content" as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.

      -

      Figure 3 -shows the result when you assign all weight to the {@link android.widget.EditText} element.

      -

      Figure 3. The {@link android.widget.EditText} widget is given all the layout weight, so it fills the remaining space in the {@link android.widget.LinearLayout}.

      -
    4. -
    - -

    Here’s how your complete content_my.xmllayout file should now look:

    +

    Here’s how your complete activity_main.xmllayout file should now look:

    -
    -<?xml version="1.0" encoding="utf-8"?>
    +
    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -   xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="horizontal"
        android:layout_width="match_parent"
    -   android:layout_height="match_parent"
    -   app:layout_behavior="@string/appbar_scrolling_view_behavior"
    -   tools:showIn="@layout/activity_my">
    +   android:layout_height="match_parent">
         <EditText android:id="@+id/edit_message"
             android:layout_weight="1"
             android:layout_width="0dp"
    @@ -406,7 +351,4 @@ that the SDK tools generated when you created the project.

    Continue to the next lesson to learn how to respond to button presses, read content -from the text field, start another activity, and more.

    - - - +from the text field, start another activity, and more.

    \ No newline at end of file diff --git a/docs/html/training/basics/firstapp/creating-project.jd b/docs/html/training/basics/firstapp/creating-project.jd index 4c2155b36314..cad32bf077d8 100644 --- a/docs/html/training/basics/firstapp/creating-project.jd +++ b/docs/html/training/basics/firstapp/creating-project.jd @@ -14,36 +14,19 @@ next.link=running-app.html
    -

    This lesson teaches you to

    - -
      -
    1. Create a Project with Android Studio
    2. -
    -

    You should also read

    -

    An Android project contains all the files that comprise the source code for your Android -app.

    - -

    This lesson -shows how to create a new project either using Android Studio or using the -SDK tools from a command line.

    - -

    Note: You should already have Android Studio or the Android SDK -command-line tools installed. If not, download them before you start this -lesson.

    - - -

    Create a Project with Android Studio

    +

    This lesson shows you how to create a new Android project with + Android Studio and describes some + of the files in the project.

    1. In Android Studio, create a new project: @@ -54,11 +37,12 @@ lesson.

      Project. The Create New Project screen appears.
    2. -
    3. Fill out the fields on the screen, and click Next. -

      It is easier to follow these lessons if you use the same values as shown.

      +
    4. Fill out the fields on the screen. For Application Name + use "My First App". For Company Domain, use "example.com". + For the other fields, use the default values and click Next +

      Here's a brief explanation of each field:

        -
      • Application Name is the app name that appears to users. - For this project, use "My First App."
      • +
      • Application Name is the app name that appears to users.
      • Company domain provides a qualifier that will be appended to the package name; Android Studio will remember this qualifier for each new project you create.
      • Package name is the fully qualified name for the project (following the @@ -70,9 +54,8 @@ lesson.

        files.
    5. -
    6. Under Select the form factors your app will run on, check the box for - Phone and Tablet.
    7. -
    8. For Minimum SDK, select API 8: Android 2.2 (Froyo). +
    9. Under Target Android Devices, accept the default values + and click Next.

      The Minimum Required SDK is the earliest version of Android that your app supports, indicated using the API level. To support as many devices as possible, you should set this to the lowest @@ -80,8 +63,13 @@ lesson.

      app is possible only on newer versions of Android and it's not critical to the app's core feature set, you can enable the feature only when running on the versions that support it (as discussed in - Supporting Different Platform Versions).

    10. -
    11. Leave all of the other options (TV, Wear, and Glass) unchecked and click Next.
    12. + Supporting Different Platform Versions).

      + + +
    13. Under Add an Activity to Mobile, select Empty + Activity and click Next. +
    14. + -
    15. Under Add an activity to <template>, - select Basic Activity and click Next. -
    16. - -
    17. Under Customize the Activity, change the - Activity Name to MyActivity. The Layout - Name changes to activity_my, and the Title - to MyActivity. The Menu Resource Name is - menu_my. -
    18. -
    19. Click the Finish button to create the project. -
    20. +
    21. Under Customize the Activity, accept the default values + and click Finish.

    Your Android project is now a basic "Hello World" app that contains some default files. Take a moment to review the most important of these:

    -
    app/src/main/res/layout/activity_my.xml
    -
    This XML layout file is for the activity you added when you created the project - with Android Studio. Following the New Project workflow, Android Studio presents this file - with both a text - view and a preview of the screen UI. The file contains some default interface elements - from the material design library, including the - app bar and a floating action button. - It also includes a separate layout file with the main content.
    - -
    app/src/main/res/layout/content_my.xml
    -
    This XML layout file resides in {@code activity_my.xml}, and contains some settings and - a {@code TextView} element that displays the message, "Hello world!".
    - -
    app/src/main/java/com.mycompany.myfirstapp/MyActivity.java
    -
    A tab for this file appears in Android Studio when the New Project workflow finishes. When you - select the file you see the class definition for the activity you created. When you build and - run the app, the {@link android.app.Activity} class starts the activity and loads the layout file - that says "Hello World!"
    +
    app/src/main/java/com.example.myfirstapp/MainActivity.java
    +
    This file appears in Android Studio after the New Project wizard finishes. + It contains the class definition for the activity you created earlier. When you build + and run the app, the {@link android.app.Activity} starts and loads the + layout file that says "Hello World!"
    + +
    app/src/main/res/layout/activity_main.xml
    +
    This XML file defines the layout of the activity. It contains a {@code TextView} + element with the text "Hello world!".
    +
    app/src/main/AndroidManifest.xml
    The manifest file describes the fundamental characteristics of the app and defines each of its components. You'll revisit @@ -143,15 +113,15 @@ moment to review the most important of these:

    • compiledSdkVersion is the platform version against which you will compile your app. By default, this is set to the latest version of Android available in your SDK. - (It should be Android 4.1 or greater; if you don't have such a version available, you must - install one using the SDK Manager.) + By default, this is set to the latest version of Android SDK installed on your + development machine. You can still build your app to support older versions, but setting this to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.
    • applicationId is the fully qualified package name for your application that - you specified during the New Project workflow.
    • + you specified in the New Project wizard.
    • minSdkVersion is the Minimum SDK version you specified during the New Project - workflow. This is the earliest version of the Android SDK that your app supports.
    • + wizard. This is the earliest version of the Android SDK that your app supports.
    • targetSdkVersion indicates the highest version of Android with which you have tested your application. As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level and @@ -172,8 +142,8 @@ moment to review the most important of these:

      for various densities.
    layout/
    -
    Directory for files that define your app's user interface like {@code activity_my.xml}, - discussed above, which describes a basic layout for the {@code MyActivity} +
    Directory for files that define your app's user interface like {@code activity_main.xml}, + discussed above, which describes a basic layout for the {@code MainActivity} class.
    menu/
    Directory for files that define your app's menu items.
    diff --git a/docs/html/training/basics/firstapp/index.jd b/docs/html/training/basics/firstapp/index.jd index cb5073f95c01..48b7190b73c0 100644 --- a/docs/html/training/basics/firstapp/index.jd +++ b/docs/html/training/basics/firstapp/index.jd @@ -23,25 +23,10 @@ helpoutsWidget=true

    Welcome to Android application development!

    -

    This class teaches you how to build your first Android app. You’ll learn how to create an Android -project and run a debuggable version of the app. You'll also learn some fundamentals of Android app -design, including how to build a simple user interface and handle user input.

    - -

    Set Up Your Environment

    - -

    Before you start this class, be sure you have your development environment set up. You need -to:

    -
      -
    1. Download Android Studio.
    2. -
    3. Download the latest SDK tools and platforms using the - SDK Manager.
    4. -
    - -

    Note: Although most of this training class -expects that you're using Android Studio, some procedures include alternative -instructions for using -the SDK tools from the command line instead.

    - -

    This class uses a tutorial format to create a small Android app that teaches -you some fundamental concepts about Android development, so it's important that you follow each -step.

    +

    This class teaches you how to build your first Android app. You’ll learn how + to create an Android project with Android Studio and run a debuggable version + of the app. You'll also learn some fundamentals of Android app design, + including how to build a simple user interface and handle user input.

    + +

    Before you start this class, download and install + Android Studio.

    \ No newline at end of file diff --git a/docs/html/training/basics/firstapp/running-app.jd b/docs/html/training/basics/firstapp/running-app.jd index 21fb64d83798..e8098711b9a9 100755 --- a/docs/html/training/basics/firstapp/running-app.jd +++ b/docs/html/training/basics/firstapp/running-app.jd @@ -26,7 +26,6 @@ helpoutsWidget=true @@ -34,27 +33,20 @@ helpoutsWidget=true -

    If you followed the previous lesson to create an -Android project, it includes a default set of "Hello World" source files that allow you to -immediately run the app.

    - -

    How you run your app depends on two things: whether you have a real device running Android and -whether you're using Android Studio. This lesson shows you how to install and run your app on a -real device and on the Android emulator, and in both cases with either Android Studio or the command -line tools.

    +

    In the previous lesson, you created an + Android project. The project contains a default app that displays + "Hello World". In this lesson, you will run the app on a device or emulator.

    Run on a Real Device

    -

    If you have a device running Android, here's how to install and run your app.

    - -

    Set up your device

    +

    Set up your device as follows:

      -
    1. Plug in your device to your development machine with a USB cable. +
    2. Connect your device to your development machine with a USB cable. If you're developing on Windows, you might need to install the appropriate USB driver for your - device. For help installing drivers, see the OEM + device. For help installing drivers, see the OEM USB Drivers document.
    3. -
    4. Enable USB debugging on your device. On Android 4.0 and newer, go to +
    5. Enable USB debugging on your device by going to Settings > Developer options.

      Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go @@ -63,73 +55,61 @@ line tools.

    -

    Run the app from Android Studio

    +

    Run the app from Android Studio as follows:

    +
      -
    1. Select one of your project's files and click -Run -from the toolbar.
    2. -
    3. In the Choose Device window that appears, select the - Choose a running device radio button, select your device, and click OK - .
    4. +
    5. In Android Studio, select your project and click + Run + from the toolbar.
    6. +
    7. In the Select Deployment Target window, + select your device, and click OK.

    Android Studio installs the app on your connected device and starts it.

    Run on the Emulator

    -

    Whether you're using Android Studio or the command line, to run your app on the emulator you need -to first create an Android Virtual Device (AVD). An -AVD is a device configuration for the Android emulator that allows you to model a specific -device.

    - +

    Before you run your app on an emulator, you need to create an + Android Virtual Device (AVD) + definition. An AVD definition defines the characteristics of an Android phone, + tablet, Android Wear, or Android TV device that you want to simulate in the + Android Emulator.

    -

    Create an AVD

    +

    Create an AVD Definition as follows:

      -
    1. Launch the Android Virtual Device Manager: -
        -
      • In Android Studio, select Tools > Android > AVD Manager, or click - the AVD Manager icon in the toolbar. The - AVD Manager screen appears.
      • -
      • Or, from the command line, change directories to - sdk/ and execute: -
        tools/android avd
        -

        Note: The AVD Manager that appears - when launched from the command line is different from the version in - Android Studio, so the following instructions may not all apply.

        -
      • -
      - -
    2. +
    3. Launch the Android Virtual Device Manager by selecting + Tools > Android > AVD Manager, or by clicking + the AVD Manager icon in the toolbar.
    4. On the AVD Manager main screen, click Create Virtual Device.
    5. -
    6. In the Select Hardware window, select a device configuration, such as Nexus 6, - then click Next. +
    7. In the Select Hardware page, select a phone device, such as Nexus 6, + then click Next.
    8. -
    9. Select the desired system version for the AVD and click Next. +
    10. In the Select Image page, choose the desired system image for the AVD and + click Next.
    11. -
    12. Verify the configuration settings, then click Finish. +
    13. Verify the configuration settings (for your first AVD, leave all the + settings as they are), and then click Finish.

    For more information about using AVDs, see -Managing AVDs with AVD Manager.

    +Create and Manage Virtual Devices.

    -

    Run the app from Android Studio

    +

    Run the app from Android Studio as follows:

      -
    1. In Android Studio, select your project and click Run - from the toolbar.
    2. -
    3. In the Choose Device window, click the Launch emulator radio - button.
    4. -
    5. From the Android virtual device pull-down menu, select the emulator - you created, and click OK.
    6. +
    7. In Android Studio, select your project and click + Run + from the toolbar.
    8. +
    9. In the Select Deployment Target window, + select your emulator and click OK.
    -

    It can take a few minutes for the emulator to load itself. You may have to unlock the screen. +

    It can take a few minutes for the emulator to start. You may have to unlock the screen. When you do, My First App appears on the emulator screen.

    That's how you build and run your Android app on the emulator! To start developing, continue to the next -lesson.

    - - +lesson.

    \ No newline at end of file diff --git a/docs/html/training/basics/firstapp/starting-activity.jd b/docs/html/training/basics/firstapp/starting-activity.jd index e84e17e5d867..ebf42cbe0438 100644 --- a/docs/html/training/basics/firstapp/starting-activity.jd +++ b/docs/html/training/basics/firstapp/starting-activity.jd @@ -19,9 +19,7 @@ helpoutsWidget=true
    1. Respond to the Send Button
    2. Build an Intent
    3. -
    4. Create the Second Activity
    5. -
    6. Receive the Intent
    7. Display the Message
    @@ -33,479 +31,202 @@ helpoutsWidget=true

    After completing the previous lesson, you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some -code to MyActivity that +code to MainActivity that starts a new activity when the user clicks the Send button.

    Respond to the Send Button

      -
    1. In Android Studio, from the res/layout directory, edit the content_my.xml -file.
    2. -
    3. Add the {@code android:onClick} -attribute to the {@link android.widget.Button <Button>} element. - -

      res/layout/content_my.xml

      -
      -<Button
      -    android:layout_width="wrap_content"
      -    android:layout_height="wrap_content"
      -    android:text="@string/button_send"
      -    android:onClick="sendMessage" />
      -
      - -

      The {@code -android:onClick} attribute’s value, "sendMessage", is the name of a method in your -activity that the system calls when the user clicks the button.

      -
    4. -
    5. In the java/com.mycompany.myfirstapp directory, open the MyActivity.java file.
    6. -
    7. Within the MyActivity class, add the {@code sendMessage()} method stub shown -below. - -

      java/com.mycompany.myfirstapp/MyActivity.java

      -
      -/** Called when the user clicks the Send button */
      -public void sendMessage(View view) {
      -    // Do something in response to button
      -}
      -
      - -

      In order for the system to match this method to the method name given to {@code android:onClick}, -the signature must be exactly as shown. Specifically, the method must:

      - -
        -
      • Be public
      • -
      • Have a void return value
      • -
      • Have a {@link android.view.View} as the only parameter (this will be the {@link -android.view.View} that was clicked)
      • -
      - -
    8. -
    - -

    Next, you’ll fill in this method to read the contents of the text field and deliver that text to -another activity.

    - -

    Build an Intent

    - -
      -
    1. In MyActivity.java, inside the {@code sendMessage()} method, create an -{@link android.content.Intent} to start an activity called {@code DisplayMessageActivity} with the -following code: - -

      java/com.mycompany.myfirstapp/MyActivity.java

      -
      -public void sendMessage(View view) {
      -  Intent intent = new Intent(this, DisplayMessageActivity.class);
      -}
      -
      - - - -

      Note: The reference to {@code DisplayMessageActivity} -will raise an error if you’re using an IDE such as Android Studio because the class doesn’t exist yet. -Ignore the error for now; you’ll create the class soon.

      - -

      The constructor used here takes two parameters:

      -
        -
      • A {@link -android.content.Context} as its first parameter ({@code this} is used because the {@link -android.app.Activity} class is a subclass of {@link android.content.Context}) -
      • The {@link java.lang.Class} of the app component to which the system should deliver -the {@link android.content.Intent} (in this case, the activity that should be started) -
      - -

      Android Studio indicates that you must import the {@link android.content.Intent} class.

      - -
    2. -
    3. At the top of the file, import the {@link android.content.Intent} class: -

      java/com.mycompany.myfirstapp/MyActivity.java

      -
      -import android.content.Intent;
      -
      -

      Tip: In Android Studio, press Alt + Enter (option + return on Mac) - to import missing classes.

      -
    4. - - - -
    5. Inside the {@code sendMessage()} method, -use {@link android.app.Activity#findViewById findViewById()} to get the -{@link android.widget.EditText} element. -

      java/com.mycompany.myfirstapp/MyActivity.java

      -
      -public void sendMessage(View view) {
      -  Intent intent = new Intent(this, DisplayMessageActivity.class);
      -  EditText editText = (EditText) findViewById(R.id.edit_message);
      -}
      -
      -
    6. - -
    7. At the top of the file, import the {@link android.widget.EditText} class. -

      In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.

      -
    8. - -
    9. Assign the text to a local message variable, and use the -{@link android.content.Intent#putExtra putExtra()} method to add its text value to the intent. -

      java/com.mycompany.myfirstapp/MyActivity.java

      -
      -public void sendMessage(View view) {
      -  Intent intent = new Intent(this, DisplayMessageActivity.class);
      -  EditText editText = (EditText) findViewById(R.id.edit_message);
      -  String message = editText.getText().toString();
      -  intent.putExtra(EXTRA_MESSAGE, message);
      -}
      -
      - -

      An {@link android.content.Intent} can carry data types as key-value -pairs called extras. The {@link android.content.Intent#putExtra putExtra()} method takes the -key name in the first parameter and the value in the second parameter.

      - -
    10. -
    11. At the top of the {@code MyActivity} class, add the {@code EXTRA_MESSAGE} definition as -follows: -

      java/com.mycompany.myfirstapp/MyActivity.java

      -
      -public class MyActivity extends AppCompatActivity {
      -    public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
      -    ...
      -}
      -
      - -

      For the next activity to query the extra data, you should define the key -for your intent's extra using a public constant. It's generally a good practice to define keys for -intent extras using your app's package name as a prefix. This ensures the keys are unique, in case -your app interacts with other apps.

      - -
    12. - - - -
    13. In the {@code sendMessage()} method, to finish the intent, call the -{@link android.app.Activity#startActivity startActivity()} method, passing it the -{@link android.content.Intent} object created in step 1. - -
    - -

    With this new code, the complete {@code sendMessage()} method that's invoked by the Send -button now looks like this:

    -

    java/com.mycompany.myfirstapp/MyActivity.java

    -
    -/** Called when the user clicks the Send button */
    -public void sendMessage(View view) {
    -    Intent intent = new Intent(this, DisplayMessageActivity.class);
    -    EditText editText = (EditText) findViewById(R.id.edit_message);
    -    String message = editText.getText().toString();
    -    intent.putExtra(EXTRA_MESSAGE, message);
    -    startActivity(intent);
    -}
    -
    - -

    The system receives this call and starts an instance of the {@link android.app.Activity} -specified by the {@link android.content.Intent}. Now you need to create the -{@code DisplayMessageActivity} class in order for this to work.

    - - - - +
  • In the file res/layout/activity_main.xml, add the + {@code android:onClick} + attribute to the {@link android.widget.Button <Button>} element as + shown below: +
    <Button
    +      android:layout_width="wrap_content"
    +      android:layout_height="wrap_content"
    +      android:text="@string/button_send"
    +      android:onClick="sendMessage" />
    +    
    +

    This attribute tells the system to call the sendMessage() + method in your activity whenever a user clicks on the button.

    +
  • -

    Create the Second Activity

    +
  • In the file java/com.example.myfirstapp/MainActivity.java, + add the sendMessage() method stub as shown below: -

    All subclasses of {@link android.app.Activity} must implement the -{@link android.app.Activity#onCreate onCreate()} method. This method is where the activity receives -the intent with the message, then renders the message. Also, the -{@link android.app.Activity#onCreate onCreate()} method must define the activity -layout with the {@link android.app.Activity#setContentView setContentView()} method. This is where -the activity performs the initial setup of the activity components.

    +
    public class MainActivity extends AppCompatActivity {
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.activity_main);
    +    }
     
    -

    Create a new activity using Android Studio

    + /** Called when the user clicks the Send button */ + public void sendMessage(View view) { + // Do something in response to button + } +}
    -

    Android Studio includes a stub for the -{@link android.app.Activity#onCreate onCreate()} method when you create a new activity. The -New Android Activity window appears.

    +

    In order for the system to match this method to the method name given to {@code android:onClick}, + the signature must be exactly as shown. Specifically, the method must:

    -
      -
    1. In Android Studio, in the java directory, select the package, - com.mycompany.myfirstapp, right-click, and select - New > Activity > Blank Activity.
    2. -
    3. In the Choose options window, fill in the activity details:
        -
      • Activity Name: DisplayMessageActivity
      • -
      • Layout Name: activity_display_message
      • -
      • Title: My Message
      • -
      • Hierarchical Parent: com.mycompany.myfirstapp.MyActivity
      • -
      • Package name: com.mycompany.myfirstapp
      • +
      • Be public
      • +
      • Have a void return value
      • +
      • Have a {@link android.view.View} as the only parameter (this will be the {@link + android.view.View} that was clicked)
      -

      Click Finish.

      -
    4. - -
    5. Open the {@code DisplayMessageActivity.java} file. -

      The class already includes an implementation of the required -{@link android.app.Activity#onCreate onCreate()} method. You update the implementation of this -method later.

      - -
    - - -

    If you're developing with Android Studio, you can run the app now, but not much happens. -Clicking the Send button starts the second activity, but it uses -a default "Hello world" layout provided by the template. You'll soon update the -activity to instead display a custom text view.

    - - -

    Create the activity without Android Studio

    - -

    If you're using a different IDE or the command line tools, do the following:

    +

    Next, you’ll fill in this method to read the contents of the text field and deliver that text to +another activity.

    -
      -
    1. Create a new file named {@code DisplayMessageActivity.java} in the project's src/ -directory, next to the original {@code MyActivity.java} file.
    2. -
    3. Add the following code to the file: +

      Build an Intent

      +

      An {@link android.content.Intent} is an object that provides runtime binding + between separate components (such as two activities). The + {@link android.content.Intent} represents an app’s "intent to do something." + You can use intents for a wide variety of tasks, but in this lesson, your intent + starts another activity.

      -
      -public class DisplayMessageActivity extends AppCompatActivity {
      +

      In MainActivity.java, add the code shown below to + sendMessage():

      +
      public class MainActivity extends AppCompatActivity {
      +    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
           @Override
           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
      -        setContentView(R.layout.activity_display_message);
      -
      -        if (savedInstanceState == null) {
      -            getSupportFragmentManager().beginTransaction()
      -                .add(R.id.container, new PlaceholderFragment()).commit();
      -        }
      +        setContentView(R.layout.activity_main);
           }
       
      -    @Override
      -    public boolean onOptionsItemSelected(MenuItem item) {
      -        // Handle app bar item clicks here. The app bar
      -        // automatically handles clicks on the Home/Up button, so long
      -        // as you specify a parent activity in AndroidManifest.xml.
      -        int id = item.getItemId();
      -        if (id == R.id.action_settings) {
      -            return true;
      -        }
      -        return super.onOptionsItemSelected(item);
      +    /** Called when the user clicks the Send button */
      +    public void sendMessage(View view) {
      +        Intent intent = new Intent(this, DisplayMessageActivity.class);
      +        EditText editText = (EditText) findViewById(R.id.edit_message);
      +        String message = editText.getText().toString();
      +        intent.putExtra(EXTRA_MESSAGE, message);
      +        startActivity(intent);
           }
      +}
      - /** - * A placeholder fragment containing a simple view. - */ - public static class PlaceholderFragment extends Fragment { - - public PlaceholderFragment() { } +

      Note: Android Studio will display + Cannot resolve symbol errors because the code references classes + like {@link android.content.Intent} and {@link android.widget.EditText} + that have not been imported. To import these classes, you can either 1) + use Android Studio's "import class" functionality by pressing Alt + Enter + (Option + Return on Mac) or 2) manually add import statements at the top of + the file.

      - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_display_message, - container, false); - return rootView; - } - } -} -
      +

      There’s a lot going on in sendMessage(), so let’s explain + what's going on.

      -

      Note: If you are using an IDE other than Android Studio, your project -does not contain the {@code activity_display_message} layout that's requested by -{@link android.app.Activity#setContentView setContentView()}. That's OK because -you will update this method later and won't be using that layout.

      +

      The {@link android.content.Intent} constructor takes two parameters:

      +
        +
      • A {@link android.content.Context} as its first parameter ({@code this} + is used because the {@link android.app.Activity} class is a subclass of + {@link android.content.Context}) +
      • The {@link java.lang.Class} of the app component to which the system + should deliver the {@link android.content.Intent} (in this case, the + activity that should be started). +

        Note: The reference to + DisplayMessageActivity will raise an error in Android Studio + because the class doesn’t exist yet. Ignore the error for now; you’ll + create the class soon.

        +
      -
    4. +

      The {@link android.content.Intent#putExtra(String, String) putExtra()} + method adds the EditText's value to the intent. An Intent + can carry data types as key-value pairs called extras. Your key is a + public constant EXTRA_MESSAGE because the next + activity uses the key to retrive the text value. It's a good practice to + define keys for intent extras using your app's package name as a prefix. This + ensures the keys are unique, in case your app interacts with other apps.

      -
    5. To your {@code strings.xml} file, add the new activity's title as follows: -
      -<resources>
      -    ...
      -    <string name="title_activity_display_message">My Message</string>
      -</resources>
      -
      -
    6. +

      The {@link android.app.Activity#startActivity(Intent) startActivity()} + method starts an instance of the DisplayMessageActivity specified + by the {@link android.content.Intent}. Now you need to create the class.

      -
    7. In your manifest file, AndroidManifest.xml, within the Application -element, add the -{@code } element -for your {@code DisplayMessageActivity} class, as follows: - -
      -<application ... >
      -    ...
      -    <activity
      -        android:name="com.mycompany.myfirstapp.DisplayMessageActivity"
      -        android:label="@string/title_activity_display_message"
      -        android:parentActivityName="com.mycompany.myfirstapp.MyActivity" >
      -        <meta-data
      -            android:name="android.support.PARENT_ACTIVITY"
      -            android:value="com.mycompany.myfirstapp.MyActivity" />
      -    </activity>
      -</application>
      -
      +

      Create the Second Activity

      -
    8. +
        +
      1. In the Project window, right-click the app folder and select + New > Activity > Empty Activity.
      2. +
      3. In the Configure Activity window, enter + "DisplayMessageActivity" for Activity Name and click + Finish +
      -

      The {@code -android:parentActivityName} attribute declares the name of this activity's parent activity -within the app's logical hierarchy. The system uses this value -to implement default navigation behaviors, such as Up navigation on -Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for -older versions of Android by using the -Support Library and adding -the {@code -} element as shown here.

      - -

      Note: Your Android SDK should already include -the latest Android Support Library, which you installed during the -Adding SDK Packages step. -When using the templates in Android Studio, the Support Library is automatically added to your app project -(you can see the library's JAR file listed under Android Dependencies). If you're not using -Android Studio, you need to manually add the library to your project—follow the guide for setting up the Support Library -then return here.

      - -

      If you're using a different IDE than Android Studio, don't worry that the app won't yet compile. -You'll soon update the activity to display a custom text view.

      - - -

      Receive the Intent

      - -

      Every {@link android.app.Activity} is invoked by an {@link android.content.Intent}, regardless of -how the user navigated there. You can get the {@link android.content.Intent} that started your -activity by calling {@link android.app.Activity#getIntent()} and retrieve the data contained -within the intent.

      +

      Android Studio automatically does three things:

      +
        +
      • Creates the class DisplayMessageActivity.java with an + implementation of the required {@link android.app.Activity#onCreate(Bundle) onCreate()} + method.
      • +
      • Creates the corresponding layout file activity_display_message.xml +
      • +
      • Adds the required + <activity> + element in AndroidManifest.xml. +
      -
        -
      1. In the java/com.mycompany.myfirstapp directory, edit the - {@code DisplayMessageActivity.java} file.
      2. -
      3. Get the intent and assign it to a local variable. -
        -Intent intent = getIntent();
        -
        -
      4. -
      5. At the top of the file, import the {@link android.content.Intent} class. -

        In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.

        -
      6. -
      7. Extract the message delivered by {@code MyActivity} with the -{@link android.content.Intent#getStringExtra getStringExtra()} method. -
        -String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
        -
        -
      8. -
      +

      If you run the app and click the Send button on the first activity, the + second activity starts but is empty. This is because the second activity uses + the default empty layout provided by the template.

      Display the Message

      +

      Now you will modify the second activity to display the message that was passed +by the first activity.

        -
      1. In the res/layout directory, edit the {@code content_display_message.xml} file.
      2. -
      3. Add an {@code android:id} attribute to the {@code RelativeLayout}. -You need this attribute to reference the object from your app code.
      4. - -
        -< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -...
        -android:id="@+id/content">
        -</RelativeLayout>
        -
        -
      5. Switch back to editing {@code DisplayMessageActivity.java}.
      6. - - -
      7. In the {@link android.app.Activity#onCreate onCreate()} method, create a {@link android.widget.TextView} object. -
        -TextView textView = new TextView(this);
        -
        -
      8. -
      9. Set the text size and message with {@link android.widget.TextView#setText setText()}. -
        -textView.setTextSize(40);
        -textView.setText(message);
        -
        -
      10. -
      11. Add the {@link android.widget.TextView} to the {@link android.widget.RelativeLayout} -identified by {@code R.id.content}. -
        -RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
        -layout.addView(textView);
        -
        -
      12. -
      13. At the top of the file, import the {@link android.widget.TextView} class. -

        In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.

        -
      14. -
      - -

      The complete {@link android.app.Activity#onCreate onCreate()} method for {@code -DisplayMessageActivity} now looks like this:

      - -
      -@Override
      +  
    9. In {@code DisplayMessageActivity.java}, add the following code to the + onCreate() method: +
      @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_display_message);
      -   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      -   setSupportActionBar(toolbar);
      -
      -   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
      -   fab.setOnClickListener(new View.OnClickListener() {
      -       @Override
      -       public void onClick(View view) {
      -           Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
      -                   .setAction("Action", null)
      -                   .show();
      -       }
      -   });
      -   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       
          Intent intent = getIntent();
      -   String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
      +   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
          TextView textView = new TextView(this);
          textView.setTextSize(40);
          textView.setText(message);
       
      -   RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
      +   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
          layout.addView(textView);
      -
      +}
    10. + +
    11. Press Alt + Enter (option + return on Mac) to import missing classes.
    12. +
    + +

    There’s a lot going on here, so let’s explain:

    + +
      +
    1. The call {@link android.app.Activity#getIntent()} grabs the intent + that started the activity. Every {@link android.app.Activity} is invoked by an + {@link android.content.Intent}, regardless of how the user navigated there. + The call {@link android.content.Intent#getStringExtra(String) getStringExtra()} + retrieves the data from the first activity.
    2. +
    3. You programmatically create a {@link android.widget.TextView} and set + its size and message. +
    4. +
    5. You add the TextView to the layout identified by + {@code R.id.activity_display_message}. You cast the layout to + {@link android.view.ViewGroup} because it is the superclass of all layouts and + contains the {@link android.view.ViewGroup#addView(View) addView()} + method.
    6. +
    + +

    Note: The XML layout generated by previous + versions of Android Studio might not include the android:id + attribute. The call findViewById() will fail if the layout + does not have the android:id attribute. If this is the case, + open activity_display_message.xml and add the attribute + android:id="@+id/activity_display_message" to the layout element. +

    You can now run the app. When it opens, type a message in the text field, and click Send. The second activity replaces the first one on the screen, showing @@ -513,8 +234,4 @@ the message you entered in the first activity.

    That's it, you've built your first Android app!

    -

    To learn more, follow the link below to the next class.

    - - - - +

    To learn more, follow the link below to the next class.

    \ No newline at end of file -- 2.11.0