Android App to Set Page Reading Goals
Build Your Beginning Android App in Java
1. Welcome!
In this codelab, you'll learn how to build and run your first Android app in the Coffee programming language. (If you're looking for the Kotlin version of this codelab, you tin go hither.)
What you must know already
This codelab is written for programmers and assumes that you know either the Java or Kotlin programming language. If y'all are an experienced programmer and practiced at reading code, you will likely be able to follow this codelab, fifty-fifty if you don't have much experience with Java.
What you lot'll learn
- How to use Android Studio to build your app.
- How to run your app on a device or in the emulator.
- How to add interactive buttons.
- How to brandish a second screen when a push is pressed.
Utilize Android Studio and Coffee to write Android apps
You write Android apps in the Java programming linguistic communication using an IDE called Android Studio. Based on JetBrains' IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android evolution.
To piece of work through this codelab, you will demand a computer that can run Android Studio three.6 or college (or already has Android Studio 3.6 or higher installed).
ii. Install Android Studio
You tin download Android Studio 3.6 from the Android Studio page.
Android Studio provides a consummate IDE, including an advanced code editor and app templates. It as well contains tools for development, debugging, testing, and performance that make information technology faster and easier to develop apps. You can use Android Studio to exam your apps with a large range of preconfigured emulators, or on your own mobile device. You lot tin also build production apps and publish apps on the Google Play shop.
Android Studio is bachelor for computers running Windows or Linux, and for Macs running macOS. The OpenJDK (Java Evolution Kit) is bundled with Android Studio.
The installation is similar for all platforms. Any differences are noted below.
- Navigate to the Android Studio download page and follow the instructions to download and install Android Studio.
- Take the default configurations for all steps, and ensure that all components are selected for installation.
- Afterward the install is complete, the setup sorcerer downloads and installs additional components, including the Android SDK. Be patient, because this process might take some time, depending on your internet speed.
- When the installation completes, Android Studio starts, and you are ready to create your first project.
3. Task: Create your first project
In this footstep, you will create a new Android projection for your offset app. This simple app displays the string "Hello Earth" on the screen of an Android virtual or physical device.
Hither's what the finished app volition look like:
What y'all'll learn
- How to create a project in Android Studio.
- How to create an emulated Android device.
- How to run your app on the emulator.
- How to run your app on your ain physical device, if y'all have one.
Step 1: Create a new projection
- Open Android Studio.
- In the Welcome to Android Studio dialog, click Start a new Android Studio project.
- Select Basic Activity (not the default). Click Next.
- Give your application a name such as My First App.
- Brand sure the Language is set to Java.
- Leave the defaults for the other fields.
- Click Terminate.
Later these steps, Android Studio:
- Creates a folder for your Android Studio project called MyFirstApp. This is usually in a folder called AndroidStudioProjects beneath your dwelling directory.
- Builds your project (this may take a few moments). Android Studio uses Gradle as its build system. You tin can follow the build progress at the bottom of the Android Studio window.
- Opens the code editor showing your project.
Step 2: Get your screen ready
When your project kickoff opens in Android Studio, there may be a lot of windows and panes open. To make it easier to go to know Android Studio, here are some suggestions on how to customize the layout.
- If there's a Gradle window open on the right side, click on the minimize button (—) in the upper right corner to hide it.
- Depending on the size of your screen, consider resizing the pane on the left showing the project folders to take up less space.
At this betoken, your screen should expect a fleck less cluttered, like to the screenshot shown beneath.
Step 3: Explore the projection structure and layout
The upper left of the Android Studio window should look similar to the following diagram:
Based on you selecting the Basic Activity template for your project, Android Studio has set upward a number of files for you. You can look at the hierarchy of the files for your app in multiple ways, one is in Project view. Project view shows your files and folders structured in a way that is convenient for working with an Android project. (This does not always match the file hierarchy! To meet the file hierarchy, choose the Projection files view by clicking (three).)
- Double-click the app (1) folder to aggrandize the hierarchy of app files. (See (ane) in the screenshot.)
- If you click Project (2), yous can hide or show the Project view. You might need to select View > Tool Windows to run across this choice.
- The current Projection view selection (3) is Project > Android.
In the Projection > Android view you come across three or four top-level folders beneath your app binder: manifests, java, coffee (generated) and res. Y'all may not see java (generated) right away.
- Expand the manifests folder.
This folder contains AndroidManifest.xml . This file describes all the components of your Android app and is read by the Android runtime system when your app is executed. two. Expand the java folder. All your Coffee language files are organized here. The java binder contains iii subfolders:
com.instance.myfirstapp: This folder contains the Java source code files for your app.
com.example.myfirstapp (androidTest): This binder is where you would put your instrumented tests, which are tests that run on an Android device. It starts out with a skeleton exam file.
com.example.myfirstapp (examination): This folder is where you lot would put your unit tests. Unit tests don't need an Android device to run. It starts out with a skeleton unit test file. 3. Expand the res folder. This folder contains all the resources for your app, including images, layout files, strings, icons, and styling. It includes these subfolders:
drawable: All your app's images will be stored in this folder.
layout: This folder contains the UI layout files for your activities. Currently, your app has one activeness that has a layout file chosen activity_main.xml. It as well contains content_main.xml, fragment_first.xml, and fragment_second.xml.
carte du jour: This folder contains XML files describing whatever menus in your app.
mipmap: This folder contains the launcher icons for your app.
navigation: This folder contains the navigation graph, which tells Android Studio how to navigate between different parts of your application.
values: This folder contains resource, such equally strings and colors, used in your app.
Step four: Create a virtual device (emulator)
In this task, you will use the Android Virtual Device (AVD) director to create a virtual device (or emulator) that simulates the configuration for a particular type of Android device.
The outset step is to create a configuration that describes the virtual device.
- In Android Studio, select Tools > AVD Director, or click the AVD Director icon in the toolbar.
- Click +Create Virtual Device. (If you accept created a virtual device earlier, the window shows all of your existing devices and the +Create Virtual Device button is at the bottom.) The Select Hardware window shows a list of pre-configured hardware device definitions.
- Cull a device definition, such equally Pixel ii, and click Next. (For this codelab, information technology actually doesn't matter which device definition you pick).
- In the System Image dialog, from the Recommended tab, choose the latest release. (This does matter.)
- If a Download link is visible side by side to a latest release, it is not installed yet, and yous need to download information technology first. If necessary, click the link to showtime the download, and click Side by side when it's done. This may have a while depending on your connection speed.
- In the side by side dialog box, accept the defaults, and click Cease.
The AVD Managing director now shows the virtual device you lot added.
- If the Your Virtual Devices AVD Manager window is still open up, go ahead and close information technology.
Step five: Run your app on your new emulator
- In Android Studio, select Run > Run 'app' or click the Run icon in the toolbar.
The icon will change when your app is already running.
- In Run > Select Device, under Available devices, select the virtual device that you just configured. This menu likewise appears in the toolbar.
The emulator starts and boots just similar a physical device. Depending on the speed of your computer, this may have a while. You tin look in the minor horizontal condition bar at the very bottom of Android Studio for messages to see the progress.
| Letters that might appear briefly in the status bar | ||
| Gradle build running | | |
| Waiting for target device to come up on line | | |
| Installing APK | | |
| Launching activity | | |
Once your app builds and the emulator is ready, Android Studio uploads the app to the emulator and runs it. You should see your app every bit shown in the following screenshot.
Step 6: Run your app on a device (if yous have ane)
What you demand:
- An Android device such as a phone or tablet.
- A information cable to connect your Android device to your computer via the USB port.
- If you lot are using a Linux or Windows OS, you may need to perform additional steps to run your app on a hardware device. Check the Run Apps on a Hardware Device documentation. On Windows, you lot may need to install the appropriate USB driver for your device. See OEM USB Drivers.
Run your app on a device
To let Android Studio communicate with your device, yous must plow on USB Debugging on your Android device.
On Android 4.two and college, the Programmer options screen is hidden by default. To evidence Developer options and enable USB Debugging:
- On your device, open Settings > About phone and tap Build number vii times.
- Render to the previous screen (Settings). Developer options appears at the bottom of the list. Tap Developer options.
- Enable USB Debugging.
Now you can connect your device and run the app from Android Studio.
- Connect your device to your development motorcar with a USB cable. On the device, you might need to agree to allow USB debugging from your evolution device.
- In Android Studio, click Run
in the toolbar at the tiptop of the window. (You might need to select View > Toolbar to see this selection.) The Select Deployment Target dialog opens with the list of available emulators and connected devices. - Select your device, and click OK. Android Studio installs the app on your device and runs information technology.
Troubleshooting
If you're stuck, quit Android Studio and restart it.
If Android Studio does not recognize your device, try the following:
- Disconnect your device from your evolution machine and reconnect it.
- Restart Android Studio.
If your computer yet does not discover the device or declares information technology "unauthorized":
- Disconnect the device.
- On the device, open Settings->Developer Options.
- Tap Revoke USB Debugging authorizations.
- Reconnect the device to your computer.
- When prompted, grant authorizations.
If you are still having trouble, check that you installed the appropriate USB commuter for your device. See the Using Hardware Devices documentation.
Cheque the troubleshooting section in the Android Studio documentation.
Step 7: Explore the app template
When y'all created the projection and selected Basic Activity, Android Studio set a number of files, folders, and too user interface elements for you, so you tin can outset out with a working app and major components in place. This makes it easier to build your application.
Looking at your app on the emulator or your device, in improver to the Next push, observe the floating action button with an email icon.
If you tap that button, you'll encounter information technology has been ready to briefly testify a message at the bottom of the screen. This bulletin infinite is called a snackbar, and it'due south one of several ways to notify users of your app with cursory data.
At the acme right of the screen, at that place's a menu with 3 vertical dots.
If you tap on that, you'll see that Android Studio has also created an options carte with a Settings particular. Choosing Settings doesn't do anything yet, but having it gear up for you makes it easier to add user-configurable settings to your app.
Afterward in this codelab, you'll look at the Next button and change the way it looks and what it does.
4. Job: Explore the layout editor
Generally, each screen in your Android app is associated with one or more fragments. The single screen displaying "How-do-you-do first fragment" is created by one fragment, called FirstFragment. This was generated for you when you created your new projection. Each visible fragment in an Android app has a layout that defines the user interface for the fragment. Android Studio has a layout editor where yous can create and define layouts.
Layouts are defined in XML. The layout editor lets you define and modify your layout either by coding XML or by using the interactive visual editor.
Every element in a layout is a view. In this job, you will explore some of the panels in the layout editor, and you volition larn how to alter holding of views.
What you'll larn
- How to use the layout editor.
- How to set belongings values.
- How to add string resources.
- How to add color resources.
Step one: Open the layout editor
- Find and open the layout folder (app > res > layout) on the left side in the Project console.
- Double-click
fragment_first.xml.
The panels to the right of the Projection view comprise the Layout Editor. They may be arranged differently in your version of Android Studio, but the office is the same.
On the left is a Palette (1) of views you tin can add to your app.
Below that is a Component Tree (2) showing the views currently in this file, and how they are arranged in relation to each other.
In the center is the Design editor (3) , which shows a visual representation of what the contents of the file will look like when compiled into an Android app. You can view the visual representation, the XML code, or both.
- In the upper right corner of the Blueprint editor, above Attributes (4), find the three icons that wait like this:
These represent Code (lawmaking only), Dissever (code + design), and Design (design only) views. - Try selecting the different modes. Depending on your screen size and piece of work style, y'all may prefer switching between Code and Design, or staying in Separate view. If your Component Tree disappears, hibernate and show the Palette.
Split view:
- At the lower right of the Design editor you see + and - buttons for zooming in and out. Utilize these buttons to adjust the size of what you run across, or click the zoom-to-fit button and so that both panels fit on your screen.
The Design layout on the left shows how your app appears on the device. The Blueprint layout, shown on the right, is a schematic view of the layout.
- Practice using the layout card in the top left of the design toolbar to display the design view, the blueprint view, and both views adjacent.
Depending on the size of your screen and your preference, y'all may wish to simply evidence the Pattern view or the Blueprint view, instead of both.
- Use the orientation icon to modify the orientation of the layout. This allows yous to examination how your layout will fit portrait and landscape modes.
- Use the device carte to view the layout on different devices. (This is extremely useful for testing!)
On the correct is the Attributes panel. You'll acquire about that later on.
Step 2: Explore and resize the Component Tree
- In
fragment_first.xml, await at the Component Tree. If it'due south not showing, switch the mode to Design instead of Split or Code.
This panel shows the view hierarchy in your layout, that is, how the views are arranged in relation to each other. 2. If necessary, resize the Component Tree then you can read at least part of the strings. three. Click the Hide icon at the peak correct of the Component Tree.
The Component Tree closes. 4. Bring back the Component Tree by clicking the vertical label Component Tree on the left.
Step 3: Explore view hierarchies
- In the Component Tree, discover that the root of the view hierarchy is a
ConstraintLayoutview.
Every layout must have a root view that contains all the other views. The root view is always a view group, which is a view that contains other views. A ConstraintLayout is 1 example of a view group. 2. Observe that the ConstraintLayout contains a TextView, chosen textview_first and a Button, called button_first.
- If the code isn't showing, switch to Code or Split up view using the icons in the upper right corner.
- In the XML lawmaking, notice that the root element is
<androidx.constraintlayout.widget.ConstraintLayout>. The root chemical element contains a<TextView>element and a<Push>element.
<androidx.constraintlayout.widget.ConstraintLayout ... > <TextView ... /> <Button ... /> </androidx.constraintlayout.widget.ConstraintLayout> Step iv: Change property values
- In the lawmaking editor, examine the properties in the
TextViewelement.
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello starting time fragment" ... /> - Click on the string in the text property, and y'all'll notice it refers to a string resource,
hello_first_fragment.
android:text="@cord/hello_first_fragment" - Correct-click on the property and click Get To > Declaration or Usages
values/strings.xml opens with the string highlighted.
<cord name="hello_first_fragment">Hullo starting time fragment</string> - Change the value of the
cordproperty toHello World!. - Switch back to
fragment_first.xml. - Select
textview_firstin the Component Tree.
- Look at the Attributes panel on the correct, and open the Alleged Attributes section if needed.
- In the text field of the
TextViewin Attributes, find it still refers to the string resource@string/hello_first_fragment. Having the strings in a resources file has several advantages. You can change the value of string without having to change any other code. This simplifies translating your app to other languages, considering your translators don't have to know annihilation about the app lawmaking.
- Run the app to run into the modify you lot fabricated in strings.xml. Your app now shows "Hello World!".
Step 5: Modify text display backdrop
- With
textview_firstall the same selected in the Component Tree, in the layout editor, in the list of attributes, under Common Attributes, aggrandize the textAppearance field. (You may demand to whorl down to discover it.)
- Modify some of the text appearance backdrop. For example, modify the font family, increase the text size, and select assuming style. (You might need to gyre the panel to run across all the fields.)
- Change the text color. Click in the textColor field, and enter
g.
A bill of fare pops upward with possible completion values containing the letter g. This list includes predefined colors.
- Select @android:color/darker_gray and press Enter.
Below is an instance of the textAppearance attributes afterward making some changes.
- Look at the XML for the
TextView. You see that the new backdrop have been added.
<TextView android:id="@+id/textview_first" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-condensed" android:text="@string/hello_first_fragment" android:textColor="@android:colour/darker_gray" android:textSize="30sp" android:textStyle="assuming" - Run your app again and run across the changes practical to your Hi World! string
Footstep six: Display all attributes
- In the Attributes panel, curl downward until you find All Attributes.
- Scroll through the list to become an thought of the attributes you could set for a
TextView.
5. Job: Add color resources
So far you have learned how to modify property values. Next, you will learn how to create more resource like the string resources you worked with earlier. Using resource enables y'all to utilize the same values in multiple places, or to ascertain values and take the UI update automatically whenever the value is inverse.
What you'll larn
- How resources are divers.
- Adding and using color resources.
- The results of changing layout acme and width.
Pace one: Add colour resources
First, you lot'll learn how to add together new color resources.
- In the Project console on the left, double-click on res > values > colors.xml to open the color resource file.
<resources> <color name="colorPrimary">#6200EE</colour> <colour proper name="colorPrimaryDark">#3700B3</color> <color proper name="colorAccent">#03DAC5</color> </resources> The colors.xml file opens in the editor. So far, three colors take been defined. These are the colors you lot can encounter in your app layout, for example, majestic for the app bar.
- Become dorsum to
fragment_first.xmlso you tin see the XML code for the layout. - Add a new belongings to the
TextViewcalledandroid:groundwork, and start typing to ready its value to@color. Y'all can add this property anywhere within theTextViewcode.
A menu pops upward offering the predefined color resources:
- Choose @color/colorPrimaryDark.
- Change the property
android:textColorand requite it a value of@android:color/white.
The Android framework defines a range of colors, including white, so you don't have to define white yourself. 6. In the layout editor, you can see that the TextView now has a dark blue background, and the text is displayed in white.
Step 2: Add together a new color to utilize as the screen background color
- Back in
colors.xml, create a new color resources calledscreenBackground:
<color name="screenBackground">#FFEE58</color> A Color can be divers as three hexadecimal numbers (#00-#FF, or 0-255) representing the red, blue, and green (RGB) components. The color yous only added is xanthous. Notice that the colors respective to the lawmaking are displayed in the left margin of the editor.
Annotation that a color can also be defined including an alpha value (#00-#FF) which represents the transparency (#00 = 0% = fully transparent, #FF = 100% = fully opaque). When included, the alpha value is the first of 4 hexadecimal numbers (ARGB).
The alpha value is a measure of transparency. For instance, #88FFEE58 makes the colour semi-transparent, and if you apply #00FFEE58, it'south fully transparent and disappears from the left-hand bar.
- Become back to
fragment_first.xml. - In the Component Tree, select the
ConstraintLayout.
- In the Attributes panel, select the background property and printing Enter. Blazon "c" in the field that appears.
- In the menu of colors that appears, select @color/screenBackground. Press Enter to complete the selection.
- Click on the yellow patch to the left of the color value in the background field.
It shows a listing of colors defined in colors.xml. Click the Custom tab to choose a custom colour with an interactive color chooser.
- Feel free to change the value of the screenBackground color, merely make sure that the concluding color is noticeably unlike from the
colorPrimaryandcolorPrimaryDarkcolors.
Pace 3: Explore width and top backdrop
Now that you have a new screen background color, y'all will employ it to explore the effects of changing the width and summit properties of views.
- In
fragment_first.xml, in the Component Tree, select theConstraintLayout.
- In the Attributes console, find and aggrandize the Layout department.
The layout_width and layout_height properties are both set to match_parent. The ConstraintLayout is the root view of this Fragment, so the "parent" layout size is finer the size of your screen.
- Notice that the entire groundwork of the screen uses the screenBackground color.
- Select
textview_first. Currently the layout width and pinnacle are wrap_content, which tells the view to be just large plenty to enclose its content (plus padding) - Change both the layout width and layout top to match_constraint, which tells the view to be every bit big as any it'due south constrained to.
The width and height show 0dp, and the text moves to the upper left, while the TextView expands to match the ConstraintLayout except for the push. The button and the text view are at the same level in the view hierarchy inside the constraint layout, and so they share space.
- Explore what happens if the width is match_constraint and the height is wrap_content and vice versa. You can as well change the width and height of the button_first.
- Fix both the width and meridian of the
TextViewand thePushdorsum to wrap_content.
6. Task: Add together views and constraints
In this task, you will add two more buttons to your user interface, and update the existing push button, equally shown beneath.
What you'll learn
- How to add new views to your layout.
- How to constrain the position of a view to another view.
Pace i: View constraint properties
- In
fragment_first.xml, expect at the constraint backdrop for theTextView.
app:layout_constraintBottom_toTopOf="@id/button_first" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" These properties define the position of the TextView. Read them advisedly.
You lot tin constrain the peak, bottom, left, and correct of a view to the pinnacle, bottom, left, and right of other views.
- Select
textview_firstin the Component Tree and await at the Constraint Widget in the Attributes panel.
The foursquare represents the selected view. Each of the grayness dots represents a constraint, to the meridian, bottom, left, and right; for this example, from the TextView to its parent, the ConstraintLayout, or to the Next push for the bottom constraint. 3. Notice that the pattern and blueprint views also testify the constraints when a detail view is selected. Some of the constraints are jagged lines, but the ane to the Next button is a squiggle, because information technology's a little unlike. You'll learn more about that in a scrap.
Step two: Add buttons and constrain their positions
To learn how to utilise constraints to connect the positions of views to each other, you will add buttons to the layout. Your first goal is to add together a push button and some constraints, and modify the constraints on the Next push button.
- Discover the Palette at the top left of the layout editor. Move the sides if y'all need to, so that you can run into many of the items in the palette.
- Click on some of the categories, and scroll the listed items if needed to get an idea of what's available.
- Select Button, which is near the top, and drag and driblet it onto the blueprint view, placing information technology underneath the
TextViewnear the other button.
Notice that a Push has been added to the Component Tree under ConstraintLayout.
Step 3: Add a constraint to the new button
You will now constrain the top of the push to the bottom of the TextView.
- Motion the cursor over the circumvolve at the top of the
Button.
- Click and drag the circle at the acme of the
Pushonto the circle at the bottom of theTextView.
The Button moves upward to sit only beneath the TextView because the top of the push button is now constrained to the bottom of the TextView.
- Take a look at the Constraint Widget in the Layout pane of the Attributes console. It shows some constraints for the
Button, including Top -> BottomOf textView. - Take a expect at the XML code for the push button. It now includes the attribute that constrains the top of the push button to the bottom of the
TextView.
app:layout_constraintTop_toBottomOf="@+id/textview_first" - You may see a alarm, "Not Horizontally Constrained". To fix this, add a constraint from the left side of the push to the left side of the screen.
- Also add a constraint to constrain the bottom of the push button to the bottom of the screen.
Before adding another button, relabel this button then things are a piffling clearer about which button is which.
- Click on the button you just added in the design layout.
- Look at the Attributes panel on the right, and discover the id field.
- Alter the id from
pushtotoast_button.
Step four: Accommodate the Next push button
Yous volition adapt the push button labeled Next, which Android Studio created for y'all when you created the project. The constraint between information technology and the TextView looks a fiddling different, a wavy line instead of a jagged ane, with no arrow. This indicates a chain, where the constraints link two or more objects to each other, instead of just one to another. For at present, y'all'll delete the chained constraints and replace them with regular constraints.
To delete a constraint:
- In the design view or pattern view, concord the
Ctrlkey (Commandon a Mac) and movement the cursor over the circle for the constraint until the circle highlights, then click the circle.
- Or click on one of the constrained views, then right-click on the constraint and select Delete from the menu.
- Or in the Attributes panel, move the cursor over the circle for the constraint until information technology shows an x, and so click it.
If you delete a constraint and want it back, either undo the activity, or create a new constraint.
Pace five: Delete the chain constraints
- Click on the Adjacent button, and then delete the constraint from the meridian of the button to the
TextView. - Click on the
TextView, and and so delete the constraint from the bottom of the text to the Next push.
Step 6: Add new constraints
- Constrain the correct side of the Next button to the correct of the screen if it isn't already.
- Delete the constraint on the left side of the Adjacent button.
- Now constrain the tiptop and bottom of the Next button and then that the top of the push button is constrained to the bottom of the
TextViewand the lesser is constrained to the lesser of the screen. The right side of the button is constrained to the right side of the screen. - Also constrain the
TextViewto the bottom of the screen.
It may seem similar the views are jumping effectually a lot, only that's normal as y'all add and remove constraints.
Your layout should now look something like this.
- In the
fragment_first.xmllayout file, find the text belongings for thetoast_buttonbutton.
<Button android:id="@+id/toast_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" - Notice that the text
"Button"is directly in the layout field, instead of referencing a string resource equally theTextViewdoes. This will make it harder to translate your app to other languages. - To fix this, click the highlighted lawmaking. A light bulb appears on the left.
- Click the lightbulb. In the menu that pops up, select Extract string resource.
- In the dialog box that appears, change the resource name to
toast_button_textand the resource value toToastand click OK.
- Detect that the value of the
android:textproperty has changed to@string/toast_button_text.
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/toast_button_text" - Become to the res > values > strings.xml file. Detect that a new string resource has been added, named
toast_button_text.
<resource> ... <string proper noun="toast_button_text">Toast</string> </resources> - Run the app to brand certain it displays as you look information technology to.
Yous now know how to create new string resources past extracting them from existing field values. (Yous can also add new resources to the strings.xml file manually.) And you know how to alter the id of a view.
Step viii: Update the Next push
The Next button already has its text in a string resource, but you'll make some changes to the button to match its new role, which volition be to generate and display a random number.
- As you did for the Toast push, change the id of the Next button from
button_firsttorandom_buttonin the Attributes panel. - If you lot get a dialog box request to update all usages of the button, click Yes. This will fix any other references to the button in the projection code.
- In
strings.xml, right-click on theside by sidestring resources. - Select Refactor > Rename... and alter the name to
random_button_text. - Click Refactor to rename your string and close the dialog.
- Change the value of the string from
Side by sidetoRandom. - If you desire, movement
random_button_textto belowtoast_button_text.
Step ix: Add a tertiary button
Your terminal layout will take three buttons, vertically constrained the aforementioned, and evenly spaced from each other.
- In
fragment_first.xml, add another button to the layout, and drop it somewhere between the Toast button and the Random push, beneath theTextView. - Add vertical constraints the same as the other two buttons. Constrain the top of the third button to the lesser of
TextView; constrain the bottom of the third button to the bottom of the screen. - Add horizontal constraints from the third button to the other buttons. Constrain the left side of the third push to the correct side of the Toast button; constrain the right side of the third button to the left side of the Random button.
Your layout should look something like this:
- Examine the XML code for
fragment_first.xml. Do whatever of the buttons have the attributeapp:layout_constraintVertical_bias? It'south OK if you exercise not see that constraint.
The "bias" constraints allows you to tweak the position of a view to be more on i side than the other when both sides are constrained in contrary directions. For example, if both the top and bottom sides of a view are constrained to the acme and bottom of the screen, you can use a vertical bias to place the view more than towards the top than the bottom.
Here is the XML code for the finished layout. Your layout might take different margins and perchance some different vertical or horizontal bias constraints.The exact values of the attributes for the advent of the TextView might be different for your app.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout <?xml version="i.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-motorcar" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:groundwork="@color/screenBackground" tools:context=".FirstFragment"> <TextView android:id="@+id/textview_first" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" android:fontFamily="sans-serif-condensed" android:text="@string/hello_first_fragment" android:textColor="@android:colour/white" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/random_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/random_button_text" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/textview_first" /> <Button android:id="@+id/toast_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@cord/toast_button_text" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textview_first" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/random_button" app:layout_constraintStart_toEndOf="@+id/toast_button" app:layout_constraintTop_toBottomOf="@+id/textview_first" /> </androidx.constraintlayout.widget.ConstraintLayout> Step ten: Get your UI ready for the side by side job
The next task is to brand the buttons do something when they are pressed. First, you lot demand to get the UI ready.
- Change the text of the
TextViewto prove 0 (the number zero). - Change the
idof the last button you added,button2, tocount_buttonin the Attributes panel in the design editor. - In the XML, extract the string resource to
count_button_textand set the value toCount. -
The buttons should now accept the post-obit text and ids:
| Push | text | id |
| Left button | Toast | @+id/toast_button |
| Middle button | Count | @+id/count_button |
| Right button | Random | @+id/random_button |
- Run the app.
Step xi: Fix errors if necessary
The errors occur because the buttons have inverse their id and now these constraints are referencing not-existent views.
If you have these errors, fix them past updating the id of the buttons in the constraints that are underlined in reddish.
app:layout_constraintEnd_toStartOf="@+id/random_button" app:layout_constraintStart_toEndOf="@+id/toast_button" seven. Job: Update the appearance of the buttons and the TextView
Your app's layout is now basically consummate, but its appearance can be improved with a few small changes.
Pace 1: Add together new colour resource
- In
colors.xml, change the value ofscreenBackgroundto#2196F3, which is a blue shade in the Material Design palette. - Add together a new colour named
buttonBackground. Use the value#BBDEFB, which is a lighter shade in the blue palette.
<color name="buttonBackground">#BBDEFB</color> Step 2: Add a background color for the buttons
- In the layout, add a background color to each of the buttons. (You can either edit the XML in
fragment_first.xmlor use the Attributes console, whichever you prefer.)
android:background="@color/buttonBackground" Step iii: Alter the margins of the left and right buttons
- Give the Toast button a left (outset) margin of 24dp and give the Random button a right (finish) margin of 24dp. (Using start and end instead of left and correct makes these margins work for all language directions.)
One way to do this is to use the Constraint Widget in the Attributes panel. The number on each side is the margin on that side of the selected view. Blazon 24 in the field and press Enter.
Footstep 4: Update the advent of the TextView
- Remove the groundwork color of the
TextView, either by clearing the value in the Attributes panel or by removing theandroid:backgroundattribute from the XML lawmaking.
When you remove the groundwork, the view groundwork becomes transparent. 2. Increase the text size of the TextView to 72sp.
android:textSize="72sp" - Change the font-family of the
TextViewtosans-serif(if it'south not already). - Add an
app:layout_constraintVertical_biasproperty to theTextView, to bias the position of the view upward a piffling so that it is more evenly spaced vertically in the screen. Experience free to adjust the value of this constraint as yous similar. (Bank check in the design view to see how the layout looks.)
app:layout_constraintVertical_bias="0.3" - You can as well set the vertical bias using the Constraint Widget. Click and elevate the number 50 that appears on the left side, and slide information technology upwards until information technology says 30.
- Brand certain the layout_width is wrap_content, and the horizontal bias is l (
app:layout_constraintHorizontal_bias="0.v"in XML).
Step 5: Run your app
If you lot implemented all the updates, your app will await like the post-obit figure. If y'all used unlike colors and fonts, then your app will await a scrap different.
8. Task: Make your app interactive
You have added buttons to your app'southward chief screen, but currently the buttons practice nothing. In this chore, y'all will brand your buttons answer when the user presses them.
Beginning you will make the Toast button evidence a pop-up message called a toast. Next you will make the Count button update the number that is displayed in the TextView.
What you'll acquire
- How to notice a view past its ID.
- How to add click listeners for a view.
- How to fix and get holding values of a view from your code.
Step ane: Enable motorcar imports
To make your life easier, you tin can enable machine-imports and so that Android Studio automatically imports any classes that are needed by the Java code.
- In Android Studio, open up the settings editor by going to File > Other Settings > Preferences for New Projects.
- Select Automobile Imports. In the Coffee department, make certain Add together Unambiguous Imports on the wing is checked.
iii. Close the settings editor by pressing OK.
Step ii: Show a toast
In this step, y'all will attach a Java method to the Toast push to show a toast when the user presses the button. A toast is a curt message that appears briefly at the bottom of the screen.
- Open up
FirstFragment.java(app > java > com.instance.android.myfirstapp > FirstFragment).
This form has merely two methods, onCreateView() and onViewCreated(). These methods execute when the fragment starts.
Every bit mentioned before, the id for a view helps you lot identify that view distinctly from other views. Using the findViewByID() method, your code can find the random_button using its id, R.id.random_button. 2. Take a look at onViewCreated(). It sets up a click listener for the random_button, which was originally created as the Adjacent push.
view.findViewById(R.id.random_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(FirstFragment.this) .navigate(R.id.action_FirstFragment_to_SecondFragment); } }); Here is what this code does:
- Use the
findViewById()method with the id of the desired view equally an argument, then gear up a click listener on that view. - In the trunk of the click listener, utilise an action, which in this case is for navigating to another fragment, and navigate in that location. (You will learn about that later.)
- Just below that click listener, add code to set a click listener for the
toast_button, which creates and displays a toast. Here is the code:
view.findViewById(R.id.toast_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast myToast = Toast.makeText(getActivity(), "Hullo toast!", Toast.LENGTH_SHORT); myToast.bear witness(); } }); - Run the app and press the Toast button. Do you see the toasty bulletin at the lesser of the screen?
- If y'all want, excerpt the bulletin cord into a resource as you did for the button labels.
You lot have learned that to make a view interactive you demand to prepare a click listener for the view which says what to do when the view (push) is clicked on. The click listener tin either:
- Implement a small corporeality of code directly.
- Call a method that defines the desired click behavior in the activity.
Step 3: Make the Count push update the number on the screen
The method that shows the toast is very simple; it does not interact with any other views in the layout. In the next pace, you add behavior to your layout to find and update other views.
Update the Count button then that when it is pressed, the number on the screen increases past one.
- In the
fragment_first.xmllayout file, detect theidfor theTextView:
<TextView android:id="@+id/textview_first" - In
FirstFragment.java, add a click listener for thecount_buttonbelow the other click listeners inonViewCreated(). Because information technology has a trivial more work to do, have information technology call a new method,countMe().
view.findViewById(R.id.count_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { countMe(view); } }); - In the
FirstFragmentform, add the methodcountMe()that takes a unmarriedViewargument. This method volition be invoked when the Count button is clicked and the click listener chosen.
private void countMe(View view) { } - Get the value of the
showCountTextView. You will define that in the side by side stride.
... // Get the value of the text view String countString = showCountTextView.getText().toString(); - Convert the value to a number, and increment information technology.
... // Convert value to a number and increase it Integer count = Integer.parseInt(countString); count++; - Display the new value in the
TextViewby programmatically setting thetextproperty of theTextView.
... // Brandish the new value in the text view. showCountTextView.setText(count.toString()); Here is the whole method:
private void countMe(View view) { // Go the value of the text view Cord countString = showCountTextView.getText().toString(); // Catechumen value to a number and increment it Integer count = Integer.parseInt(countString); count++; // Brandish the new value in the text view. showCountTextView.setText(count.toString()); } Step four: Cache the TextView for repeated apply
You lot could call findViewById() in countMe() to notice showCountTextView. Yet, countMe() is called every time the button is clicked, and findViewById() is a relatively fourth dimension consuming method to call. So information technology is meliorate to notice the view in one case and enshroud information technology.
- In the
FirstFragmentclass before any methods, add a fellow member variable forshowCountTextViewof typeTextView.
TextView showCountTextView; - In
onCreateView(), you will callfindViewById()to get theTextViewthat shows the count. ThefindViewById()method must exist chosen on aViewwhere the search for the requested ID should get-go, and so assign the layout view that is currently returned to a new variable,fragmentFirstLayout, instead.
// Inflate the layout for this fragment View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, fake); - Call
findViewById()onfragmentFirstLayout, and specify theidof the view to find,textview_first. Cache that value inshowCountTextView.
... // Get the count text view showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first); - Return
fragmentFirstLayoutfromonCreateView().
return fragmentFirstLayout; Hither is the whole method and the declaration of showCountTextView:
TextView showCountTextView; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Packet savedInstanceState ) { // Inflate the layout for this fragment View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, faux); // Get the count text view showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first); render fragmentFirstLayout; } - Run your app. Press the Count push button and watch the count update.
9. Task: Implement the 2nd fragment
Then far, you've focused on the first screen of your app. Next, you will update the Random button to display a random number between 0 and the current count on a 2d screen.
What you lot'll acquire
- How to pass information to a second fragment.
Update the layout for the second fragment
The screen for the new fragment volition display a heading title and the random number. Hither is what the screen will look similar in the design view:
The %d indicates that role of the cord will be replaced with a number. The R is just a placeholder.
Footstep 1: Add a TextView for the random number
- Open
fragment_second.xml(app > res > layout > fragment_second.xml) and switch to Blueprint View if needed. Discover that information technology has aConstraintLayoutthat contains aTextViewand aPush button. - Remove the chain constraints between the
TextViewand thePush.
- Add another
TextViewfrom the palette and driblet information technology well-nigh the middle of the screen. ThisTextViewvolition exist used to display a random number between 0 and the current count from the commencementFragment. - Ready the
idto@+id/textview_random(textview_randomin the Attributes panel.) - Constrain the superlative edge of the new
TextViewto the bottom of the firstTextView, the left edge to the left of the screen, and the right edge to the correct of the screen, and the bottom to the top of the Previous button. - Set both width and height to wrap_content.
- Set the textColor to @android:color/white, set the textSize to 72sp, and the textStyle to bold.
- Set the text to "
R". This text is just a placeholder until the random number is generated. - Set the layout_constraintVertical_bias to 0.45.
This TextView is constrained on all edges, and then it'due south amend to use a vertical bias than margins to adjust the vertical position, to help the layout look proficient on unlike screen sizes and orientations. 10. If yous go a alert "Not Horizontally Constrained," add a constraint from the start of the button to the left side of the screen and the stop of the button to the right side of the screen.
Here is the XML code for the TextView that displays the random number:
<TextView android:id="@+id/textview_random" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="R" android:textColor="@android:color/white" android:textSize="72sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@+id/button_second" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textview_second" app:layout_constraintVertical_bias="0.45" /> - In
fragment_second.xml, selecttextview_second, which currently has the text"How-do-you-do second fragment. Arg: %ane$s"in thehello_second_fragmentstring resource. - If
android:textisn't set, ready it to thehello_second_fragmentstring resources.
android:text="@string/hello_second_fragment" - Alter the id to
textview_headerin the Attributes panel. - Set up the width to match_constraint, but gear up the elevation to wrap_content, so the summit volition change equally needed to match the elevation of the content.
- Set meridian, left and correct margins to
24dp. Left and right margins may also exist referred to as "outset" and "finish" to support localization for right to left languages. - Remove whatsoever bottom constraint.
- Ready the text color to
@color/colorPrimaryDarkand the text size to24sp. - In
strings.xml, changehello_second_fragmentto "Here is a random number between 0 and %d." - Use Refactor > Rename... to change the proper name of
hello_second_fragmenttorandom_heading.
Here is the XML code for the TextView that displays the heading:
<TextView android:id="@+id/textview_header" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="24dp" android:layout_marginLeft="24dp" android:layout_marginTop="24dp" android:layout_marginEnd="24dp" android:layout_marginRight="24dp" android:text="@string/random_heading" android:textColor="@colour/colorPrimaryDark" android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
Footstep three: Change the background color of the layout
Requite your new activity a different background color than the showtime activity:
- In
colors.xml, add a new colour resource:
<colour name="screenBackground2">#26C6DA</color> - In the layout for the second activeness,
fragment_second.xml, set the background of theConstraintLayoutto the new colour.
In the Attributes panel:
Or in XML:
android:background="@colour/screenBackground2" Your app at present has a completed layout for the second fragment. But if you run your app and press the Random button, information technology may crash. The click handler that Android Studio set for that button needs some changes. In the adjacent task, you will explore and fix this error.
Pace 4: Examine the navigation graph
When y'all created your project, y'all chose Basic Activity as the template for the new project. When Android Studio uses the Basic Activity template for a new project, information technology sets upwardly two fragments, and a navigation graph to connect the two. It also gear up a push to transport a string argument from the starting time fragment to the second. This is the push button you inverse into the Random push. And now you desire to transport a number instead of a string.
- Open up
nav_graph.xml(app > res > navigation > nav_graph.xml).
A screen similar to the Layout Editor in Design view appears. It shows the 2 fragments with some arrows between them. You can zoom with + and - buttons in the lower right, equally you did with the Layout Editor.
- You can freely move the elements in the navigation editor. For case, if the fragments appear with
SecondFragmentto the left, dragFirstFragmentto the left ofSecondFragmentand so they appear in the lodge you work with them.
Step 5: Enable SafeArgs
This volition enable SafeArgs in Android Studio.
- Open Gradle Scripts > build.gradle (Project: My Outset App)
- Find the
dependenciessection In thebuildscriptsection, and add the following lines after the otherclasspathentries:
def nav_version = "2.3.0-alpha04" classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version" - Open Gradle Scripts > build.gradle (Module: app)
- Just below the other lines that begin with apply plugin add a line to enable SafeArgs:
apply plugin: 'androidx.navigation.safeargs' - Android Studio should brandish a message about the Gradle files existence changed. Click Sync Now on the right hand side.
After a few moments, Android Studio should display a bulletin in the Sync tab that it was successful:
- Choose Build > Make Project. This should rebuild everything and so that Android Studio tin can find
FirstFragmentDirections.
Step six: Create the argument for the navigation activity
- In the navigation graph, click on
FirstFragment, and look at the Attributes console to the right. (If the panel isn't showing, click on the vertical Attributes label to the right.) - In the Actions section, it shows what activeness will happen for navigation, namely going to
SecondFragment. - Click on
SecondFragment, and await at the Attributes panel.
The Arguments section shows Nix to show.
- Click on the + in the Arguments section.
- In the Add Argument dialog, enter
myArgfor the name and set the type to Integer, then click the Add button.
Pace 7: Send the count to the second fragment
The Next/Random push button was set up by Android Studio to go from the starting time fragment to the 2d, only it doesn't send any data. In this step you'll change information technology to transport a number for the current count. You will become the current count from the text view that displays it, and pass that to the 2nd fragment.
- Open
FirstFragment.java(app > coffee > com.example.myfirstapp > FirstFragment) - Find the method
onViewCreated()and notice the code that sets up the click listener to become from the first fragment to the second. - Supersede the code in that click listener with a line to find the count text view,
textview_first.
int currentCount = Integer.parseInt(showCountTextView.getText().toString()); - Create an action with
currentCountas the argument toactionFirstFragmentToSecondFragment().
FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount); - Add a line to find the nav controller and navigate with the action you created.
NavHostFragment.findNavController(FirstFragment.this).navigate(action); Here is the whole method, including the code y'all added before:
public void onViewCreated(@NonNull View view, Packet savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.random_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int currentCount = Integer.parseInt(showCountTextView.getText().toString()); FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount); NavHostFragment.findNavController(FirstFragment.this).navigate(action); } }); view.findViewById(R.id.toast_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast myToast = Toast.makeText(getActivity(), "Hello toast!", Toast.LENGTH_SHORT); myToast.show(); } }); view.findViewById(R.id.count_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { countMe(view); } }); } - Run your app. Click the Count push a few times. At present when you press the Random push, the second screen shows the correct string in the header, but withal no count or random number, because you need to write some lawmaking to practice that.
Pace 8: Update SecondFragment to compute and display a random number
Y'all have written the code to send the current count to the second fragment. The next step is to add code to SecondFragment.java to recollect and use the current count.
- In
SecondFragment.java, add an import for navArgs to the list of imported libraries.
import androidx.navigation.fragment.navArgs; - In the
onViewCreated()method below the line that starts withsuper, add code to get the electric current count, get the string and format it with the count, and and then set it for textview_header.
Integer count = SecondFragmentArgs.fromBundle(getArguments()).getMyArg(); Cord countText = getString(R.string.random_heading, count); TextView headerView = view.getRootView().findViewById(R.id.textview_header); headerView.setText(countText); - Go a random number between 0 and the count.
Random random = new java.util.Random(); Integer randomNumber = 0; if (count > 0) { randomNumber = random.nextInt(count + 1); } - Add lawmaking to catechumen that number into a string and set information technology every bit the text for
textview_random.
TextView randomView = view.getRootView().findViewById(R.id.textview_random); randomView.setText(randomNumber.toString()); - Run the app. Press the Count button a few times, then press the Random button. Does the app display a random number in the new activity?
Congratulations, y'all have congenital your first Android app!
10. Learn more
The intention of this codelab was to go you started building Android apps. We promise you lot want to know a lot more though, like how practice I relieve information? How do I run groundwork tasks? How exercise I display a list of photos? How exercise I ...
We encourage you to go on learning. Nosotros accept more than Android courses built by Google to help you on your learning journey.
Written tutorials
- Android Developer Fundamentals teaches programmers to build Android apps. This form is also available in some schools.
- Kotlin Bootcamp codelabs class is an introduction to Kotlin for programmers. You need experience with an object oriented programming language (Coffee, C++, Python) to take this course..
- Notice more than at developer.android.com, the official Android programmer documentation from Google.
These interactive, video-based courses were created by Google experts in collaboration with Udacity. Accept these courses at your own pace in your ain time.
- Developing Android Apps in Kotlin: If yous know how to program, learn how to build Android apps. This course uses Kotlin.
- Kotlin Bootcamp for Programmers: This is an introduction to Kotlin for programmers. You demand some feel with an object oriented programming linguistic communication (Java, C++, Python) to take this course.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and lawmaking samples are licensed under the Apache two.0 License. For details, see the Google Developers Site Policies. Coffee is a registered trademark of Oracle and/or its affiliates.
Source: https://developer.android.google.cn/codelabs/build-your-first-android-app
0 Response to "Android App to Set Page Reading Goals"
Postar um comentário