This lesson shows you how to create a new Android project with Android Studio and describes some of the files in the project.
An activity is one of the distinguishing features of the Android framework. Activities provide the user with access to your app, and there may be many activities. An application will usually have a main activity for when the user launches the application, another activity for when she selects some content to view, for example, and other activities for when she performs other tasks within the app. See Activities for more information.
Here's a brief explanation of each field:
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 version available that allows your app to provide its core feature set. If any feature of your 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).
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/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 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 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 this file as you follow these lessons and add more components to your app.
app/build.gradle
Android Studio uses Gradle to compile and build your app. There is a build.gradle
file for each module of your project, as well as abuild.gradle
file for the entire project. Usually, you're only interested in the build.gradle
file for the module, in this case the app
or application module. This is where your app's build dependencies are set, including the defaultConfig
settings:
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. 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 in the New Project wizard.minSdkVersion
is the Minimum SDK version you specified during the New Project 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 thereby take advantage of new platform features. For more information, read Supporting Different Platform Versions.See Building Your Project with Gradle for more information about Gradle.
Note also the /res
subdirectories that contain the resources for your application:
drawable-
Directories for drawable resources, other than launcher icons, designed for various densities.
layout/
Directory for files that define your app's user interface like activity_main.xml
, discussed above, which describes a basic layout for theMainActivity
class.
menu/
Directory for files that define your app's menu items.
mipmap/
Launcher icons reside in the mipmap/
folder rather than the drawable/
folders. This folder contains the ic_launcher.png
image that appears when you run the default app.
values/
Directory for other XML files that contain a collection of resources, such as string and color definitions
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.
Set up your device as follows:
Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.
Run the app from Android Studio as follows:
Android Studio installs the app on your connected device and starts it.
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 Definition as follows:
For more information about using AVDs, see Create and Manage Virtual Devices.
Run the app from Android Studio as follows:
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.
In this lesson, you create a layout in XML that includes a text field and a button. In the next lesson, your app responds when the button is pressed by sending the content of the text field to another activity.
The graphical user interface for an Android app is built using a hierarchy of View
and ViewGroup
objects. View
objects are usually UI widgets such as buttons or text fields. ViewGroup
objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
Android provides an XML vocabulary that corresponds to the subclasses of View
and ViewGroup
so you can define your UI in XML using a hierarchy of UI elements.
Layouts are subclasses of the ViewGroup
. In this exercise, you'll work with a LinearLayout
.
Declaring your UI layout in XML rather than runtime code is useful for several reasons, but it's especially important so you can create different layouts for different screen sizes. For example, you can create two versions of a layout and tell the system to use one on "small" screens and the other on "large" screens. For more information, see the class about Supporting Different Devices.
Figure 1. Illustration of how ViewGroup
objects form branches in the layout and contain other View
objects.
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.
<?xml version="1.0" encoding="utf-8"?>
LinearLayout
is a view group (a subclass of ViewGroup
) that lays out child views in either a vertical or horizontal orientation, as specified by theandroid:orientation
attribute. Each child of a LinearLayout
appears on the screen in the order in which it appears in the XML.
Two other attributes, android:layout_width
and android:layout_height
, are required for all views in order to specify their size.
Because the LinearLayout
is the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "match_parent"
. This value declares that the view should expand its width or height to match the width or height of the parent view.
For more information about layout properties, see the Layout guide.
In the activity_main.xml
file, within the
element, add the following
element:
Here is a description of the attributes in the
you added:
This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
The at sign (@
) is required when you're referring to any resource object from XML. It is followed by the resource type (id
in this case), a slash, then the resource name (edit_message
).
A resource object is a unique integer name that's associated with an app resource, such as a bitmap, layout file, or string.
Every resource has a corresponding resource object defined in your project's gen/R.java
file. You can use the object names in the R
class to refer to your resources, such as when you need to specify a string value for the android:hint
attribute. You can also create arbitrary resource IDs that you associate with a view using theandroid:id
attribute, which allows you to reference that view from other code.
The SDK tools generate the R.java
file each time you compile your app. You should never modify this file by hand.
For more information, read the guide to Providing Resources.
The plus sign (+
) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project's gen/R.java
file that refers to the EditText
element. With the resource ID declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.
android:layout_width
and android:layout_height
Instead of using specific sizes for the width and height, the "wrap_content"
value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use "match_parent"
, then the EditText
element would fill the screen, because it would match the size of the parent LinearLayout
. For more information, see the Layouts guide.
This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the "@string/edit_message"
value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string.
Note: This string resource has the same name as the element ID: edit_message
. However, references to resources are always scoped by the resource type (such as id
or string
), so using the same name does not cause collisions.
By default, your Android project includes a string resource file at res/values/strings.xml
. Here, you'll add two new strings.
res/values/
directory, open strings.xml
.<?xml version="1.0" encoding="utf-8"?>My First App Enter a message Send
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, which makes the text easier to find and update. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.
For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.
Go back to the activity_main.xml
file and add a button after the
. Your file should look like this:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" />
Note: This button doesn't need the android:id
attribute, because it won't be referenced from the activity code.
The layout is currently designed so that both the EditText
and Button
widgets are only as big as necessary to fit their content, as figure 2 shows.
Figure 2. The EditText
and Button
widgets have their widths set to "wrap_content"
.
This works fine for the button, but not as well for the text field, because the user might type something longer. It would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout
with the weight property, which you can specify using theandroid:layout_weight
attribute.
The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.
In activity_main.xml
, modify the
so that the attributes look like this:
android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message" />
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. The EditText
widget is given all the layout weight, so it fills the remaining space in the LinearLayout
.
Here’s how your complete activity_main.xml
layout file should now look:
<?xml version="1.0" encoding="utf-8"?><Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" />
This layout is applied by the default Activity
class that the SDK tools generated when you created the project.
To run the app and see the results, click Run 'app' in the toolbar.
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 MainActivity
that starts a new activity when the user clicks the Send button.
res/layout/activity_main.xml
, add the android:onClick
attribute to the <Button>
element as shown below:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" />
This attribute tells the system to call the sendMessage()
method in your activity whenever a user clicks on the button.
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 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 android:onClick
, the signature must be exactly as shown. Specifically, the method must:
Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.
An Intent
is an object that provides runtime binding between separate components (such as two activities). The 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.
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_main); } /** 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); } }
Note: Android Studio will display Cannot resolve symbol
errors because the code references classes like Intent
and 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.
There’s a lot going on in sendMessage()
, so let’s explain what's going on.
The Intent
constructor takes two parameters:
Context
as its first parameter (this
is used because the Activity
class is a subclass of Context
)Class
of the app component to which the system should deliver the 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.
The 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.
The startActivity()
method starts an instance of the DisplayMessageActivity
specified by the Intent
. Now you need to create the class.
Android Studio automatically does three things:
DisplayMessageActivity.java
with an implementation of the required onCreate()
method.activity_display_message.xml
AndroidManifest.xml
.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.
Now you will modify the second activity to display the message that was passed by the first activity.
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); Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message); layout.addView(textView); }
There’s a lot going on here, so let’s explain:
getIntent()
grabs the intent that started the activity. Every Activity
is invoked by an Intent
, regardless of how the user navigated there. The call getStringExtra()
retrieves the data from the first activity.TextView
and set its size and message.TextView
to the layout identified by R.id.activity_display_message
. You cast the layout to ViewGroup
because it is the superclass of all layouts and contains the addView()
method.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 attributeandroid: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 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.
https://i-softinc.com/45/Home/Blog