Professional Documents
Culture Documents
Welcome to Training for Android developers. Here you'll find training classes that describe how to
accomplish a specific task with code samples you can re-use in your app. Classes are organized into
several groups you can see at the top-level of the left navigation.
The first training guides below teach you the essentials for Android app development. If you're a new
Android app developer, you should complete each of these classes in order.
Saving Data
How to save data on the device, whether it's temporary files, downloaded app assets, user media,
structured data, or something else.
1. Saving Key-Value Sets
2. Saving Files
3. Saving Data in SQL Databases
You might want to change the project location, but leave the other options as they are.
3. Click Next.
4. In the Target Android Devices screen, keep the default values and click Next.
If you're curious about how these SDK versions affect your app, read Supporting Different
Platform Versions.
5. In the Add an Activity to Mobile screen, select Empty Activity and click Next.
6. In the Customize the Activity screen, keep the default values and click Finish.
After some processing, Android Studio opens the IDE. Now take a moment to review the most
important files.
First, be sure the Project window is open (select View > Tool Windows > Project) and the Android
view is selected from the drop-down list at the top of that window. You can then see the following files:
app > java > com.example.myfirstapp > MainActivity.java
This is the main activity (the entry point for your app). When you build and run the app, the
system launches an instance of this Activity and loads its layout.
app > res > layout > activity_main.xml
This XML file defines the layout for the activity's UI. It contains a TextView element with the
text "Hello world!".
app > manifests > AndroidManifest.xml
The manifest file describes the fundamental characteristics of the app and defines each of its
components.
Gradle Scripts > build.gradle
You'll see two files with this name: one for the project and one for the "app" module. Each
module has its own build.gradle file, but this project currently has just one module. You'll
mostly work with the module's build.gradle file to configure how the Gradle tools compile
and build your app. For more information about this file, see Configure Your Build.
To run the app, continue to the next lesson.
Run on an emulator
Before you run your app on an emulator, you need to create an Android Virtual Device (AVD)
definition. An AVD definition specifies 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 Definition as follows:
1. Launch the Android Virtual Device Manager by selecting Tools > Android > AVD Manager, or
by clicking the AVD Manager icon in the toolbar.
2. In the Your Virtual Devices screen, click Create Virtual Device.
3. In the Select Hardware screen, select a phone device, such as Pixel, and then click Next.
4. In the System Image screen, click Download for one of the recommended system images.
Agree to the terms to complete the download.
5. After the download is complete, select the system image from the list and click Next.
6. On the next screen, leave all the configuration settings as they are and click Finish.
7. Back in the Your Virtual Devices screen, select the device you just created and click Launch
Figure 2. Illustration of how ViewGroup objects form branches in the layout and contain View
objects
Android provides an XML vocabulary for ViewGroup and View classes, so most of your UI is
defined in XML files. However, instead of teaching you to write some XML, this lesson shows you
how to create a layout using Android Studio's Layout Editor, which makes it easy to build a layout by
drag-and-dropping views.
Windows > Project (or click Project on the left side of Android Studio).
3. If your editor shows the XML source, click the Design tab at the bottom of the window.
7. Click Default Margins in the toolbar and select 16 (you can still adjust the margin for
each view later).
The Component Tree window on the bottom-left side shows the layout's hierarchy of views. In this
case, the root view is a ConstraintLayout, containing just one TextView object.
ConstraintLayout is a layout that defines the position for each view based on constraints to
sibling views and the parent layout. In this way, you can create both simple and complex layouts with a
flat view hieararchy. That is, it avoids the need for nested layouts (a layout inside a layout, as shown in
figure 2), which can increase the time required to draw the UI.
For example, you can declare the following layout (in figure 4):
Add a button
Figure 6. The button is constrained to the right side of the text box and its baseline
1. From the Palette window, click Widgets in the left pane, and then drag Button into the design
editor and drop it near the right side.
2. Create a constraint from the left side of the button to the right side of the text box.
3. To constrain the views in a horizontal alignment, you need to create a constraint between the
text baselines. So click the button, and then click Baseline Constraint , which appears in
the design editor directly below the selected view. The baseline anchor appears inside the
button. Click-and-hold on this anchor and then drag it to the baseline anchor that appears in the
text box.
The result should look like the screenshot in figure 6.
Note: You can also create a horizontal alignment using the top or bottom edges, but the button includes
padding around its image, so the visual alignment is wrong if you align these views that way.
3.
Figure 7. The dialog to add a new string
Click Add Key to create a new string as the "hint text" for the text box.
1. Enter "edit_message" for the key name.
2. Enter "Enter a message" for the value.
3. Click OK.
4. Add another key named "button_send" with a value of "Send."
Now you can set these strings for each view. So return to the layout file by clicking activity_main.xml
in the tab bar, and add the strings as follows:
1. Click the text box in the layout and, if the Properties window isn't already visible on the right,
2. Locate the hint property and then click Pick a Resource to the right of the text box. In the
dialog that appears, double-click on edit_message from the list.
3. Still viewing the text box properties, also delete the value for the text property (currently set to
"Name").
4. Now click the button in the layout, locate the text property, click Pick a Resource, and then
select button_send.
Figure 8. Click to change the width and remove the right margin
Figure 9. The text box stretches to fill the remaining space
1. Create a constraint from the right side of the button to the right side of the parent layout. This
now defines the total width that the two views have available (which you can now fill with the
text box).
2. Add a constraint from the right side of the text box to the left side of the button. It might look
like that's already there, but you're actually adding a bidirectional constraint between the two
views. So both views are constrained to each other. This is called a chain (as indicated by the
chain betwen the views), and it enables some extra layout options.
3. Open the Properties window for the text box and then click the width indicator until set to
Match Constraints, as indicated by callout 1 in figure 8. "Match constraints" means that the
width is now determined by the horizontal constraints and margins. Therefore, the text box
stretches to fill the horizontal space.
4. However, the two views are separated by 32dp instead of 16dp, because both views have
margins. So while still viewing the text box properties, change the right margin to 0, as
indicated by callout 2 in figure 8.
Now the layout is done and should appear as shown in figure 9.
If it seems your layout did not turn out as expected, click below to see what your the XML should look
like and compare it to what you see in the Text tab.
See the final layout XML
For more information about chains and all the other things you can do with ConstraintLayout,
read Build a Responsive UI with ConstraintLayout.
in the toolbar to update the app with the new layout. Or click Run to install and run the app.
The button still does nothing. To start another activity when the button is tapped, continue to the next
lesson.
1.4 Start Another Activity
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, youll add some code to MainActivity that starts a new
activity to display the message when the user taps Send.
Note: This lesson expects you are using Android Studio 2.3 or higher.
1. In the file app > java > com.example.myfirstapp > MainActivity.java, add the
sendMessage() method stub as shown below:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
}
You may see an error because Android Studio cannot resolve the View class used as the method
argument. So click to place your cursor on the View declaration, and then perform a Quick Fix
by pressing Alt + Enter (or Option + Enter on Mac). (If a menu appears, select Import class.)
2. Now return to the activity_main.xml file to call this method from the button:
1. Click to select the button in the Layout Editor.
2. In the Properties window, locate the onClick property and select sendMessage
[MainActivity] from the drop-down list.
Now when the button is tapped, the system calls the sendMessage() method.
Take note of the details in this method that are required in order for the system to recognize it as
compatible with the android:onClick attribute. Specifically, the method must declare the
following:
Public access
A void return value
A View as the only parameter (it is the View object that was clicked)
Next, youll fill in this method to read the contents of the text field and deliver that text to another
activity.
Build an Intent
An Intent is an object that provides runtime binding between separate components, such as two
activities. The Intent represents an apps "intent to do something." You can use intents for a wide
variety of tasks, but in this lesson, your intent starts another activity.
In MainActivity.java, add the EXTRA_MESSAGE constant and the sendMessage() code, as
shown here:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Android Studio will again encounter Cannot resolve symbol errors, so press Alt + Enter (or Option +
Return on Mac). Your imports should end up as the following:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
An error remains for DisplayMessageActivity, but that's okay; you'll fix that in the next
section.
Here's what's going on in sendMessage():
If you run the app and tap the button on the first activity, the second activity starts but is empty. This is
because the second activity uses the empty layout provided by the template.
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(message);
}
2. Press Alt + Enter (or Option + Return on Mac) to import missing classes. Your imports should
end up as the following:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
Add up navigation
Each screen in your app that is not the main entrance (all screens that are not the "home" screen) should
provide navigation so the user can return to the logical parent screen in the app hierarchy by tapping the
Up button in the app bar.
All you need to do is declare which activity is the logical parent in the AndroidManifest.xml file.
So open the file at app > Manifests > AndroidManifest.xml, locate the <activity> tag for
DisplayMessageActivity and replace it with the following:
<activity android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" >
<!-- The meta-data tag is required if you support API level 15 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
The Android system now automatically adds the Up button in the app bar.
For example, the following are some different resource files for different languages:
English strings (default locale), /values/strings.xml:
<resources>
<string name="hello_world">Hello World!</string>
</resources>
Note: You can use the locale qualifier (or any configuration qualifier) on any resource type, such as if
you want to provide localized versions of your bitmap drawable. For more information, see
Localization.
Use the Resources in your App
You can reference the resources in your source code and other XML files using each resource's name
attribute.
In your source code, you can refer to a resource using the syntax R.<resource
type>.<resource name>. There are a variety of methods that accept a resource this way.
For example:
// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);
// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);
In other XML files, you can refer to a resource with the syntax @<resource type>/<resource
name> whenever the XML attribute accepts a compatible value.
For example:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/country_flag" />
To declare different layouts and bitmaps you'd like to use for different screens, you must place these
alternative resources in separate directories, similar to how you do for different language strings.
Also be aware that the screens orientation (landscape or portrait) is considered a variation of screen
size, so many apps should revise the layout to optimize the user experience in each orientation.
Note: Android automatically scales your layout in order to properly fit the screen. Thus, your layouts
for different screen sizes don't need to worry about the absolute size of UI elements but instead focus
on the layout structure that affects the user experience (such as the size or position of important views
relative to sibling views).
For example, this project includes a default layout and an alternative layout for large screens:
MyProject/
res/
layout/
main.xml
layout-large/
main.xml
The file names must be exactly the same, but their contents are different in order to provide an
optimized UI for the corresponding screen size.
Simply reference the layout file in your app as usual:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
The system loads the layout file from the appropriate layout directory based on screen size of the
device on which your app is running. More information about how Android selects the appropriate
resource is available in the Providing Resources guide.
As another example, here's a project with an alternative layout for landscape orientation:
MyProject/
res/
layout/
main.xml
layout-land/
main.xml
If you want to provide a special layout for landscape, including while on large screens, then you need
to use both the large and land qualifier:
MyProject/
res/
layout/ # default (portrait)
main.xml
layout-land/ # landscape
main.xml
layout-large/ # large (portrait)
main.xml
layout-large-land/ # large landscape
main.xml
Note: Android 3.2 and above supports an advanced method of defining screen sizes that allows you to
specify resources for screen sizes based on the minimum width and height in terms of density-
independent pixels. This lesson does not cover this new technique. For more information, read
Designing for Multiple Screens.
xhdpi: 2.0
hdpi: 1.5
mdpi: 1.0 (baseline)
ldpi: 0.75
This means that if you generate a 200x200 image for xhdpi devices, you should generate the same
resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap
based on the screen's density.
Note: Low-density (ldpi) resources arent always necessary. When you provide hdpi assets, the system
scales them down by one half to properly fit ldpi screens.
For more tips and guidelines about creating icon assets for your app, see the Iconography design guide.