Build Your Beginning Android App in Java

1. Welcome!

6cba94311109e72f.png

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.

  1. Navigate to the Android Studio download page and follow the instructions to download and install Android Studio.
  2. Take the default configurations for all steps, and ensure that all components are selected for installation.
  3. 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.
  4. 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:

72c7e6d2960f4faa.png

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

  1. Open Android Studio.
  2. In the Welcome to Android Studio dialog, click Start a new Android Studio project. c7c8a5cc4c9029b.png
  3. Select Basic Activity (not the default). Click Next. 73e63b490a2f4ae6.png
  4. Give your application a name such as My First App.
  5. Brand sure the Language is set to Java. 3ffb3ca42472b4f6.png
  6. Leave the defaults for the other fields.
  7. 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.

  1. If there's a Gradle window open on the right side, click on the minimize button () in the upper right corner to hide it. 97a3da610c1eede7.png
  2. 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.

70183da1f878e11a.png

Step 3: Explore the projection structure and layout

The upper left of the Android Studio window should look similar to the following diagram: ecabcf48b6f7b9a1.png

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).)

  1. Double-click the app (1) folder to aggrandize the hierarchy of app files. (See (ane) in the screenshot.)
  2. 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.
  3. 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.

  1. 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.

  1. In Android Studio, select Tools > AVD Director, or click the AVD Director icon in the toolbar. 1ef215721ed1bd47.png
  2. 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.
  3. 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).
  4. In the System Image dialog, from the Recommended tab, choose the latest release. (This does matter.)
  5. 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.
  1. 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.

  1. 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

  1. In Android Studio, select Run > Run 'app' or click the Run icon in the toolbar. 609c3e4473493202.png The icon will change when your app is already running. edee73c1aed2b57e.png
  1. In Run > Select Device, under Available devices, select the virtual device that you just configured. This menu likewise appears in the toolbar.

b1215d5cf034b077.png

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.

89960f5a856e1aa7.png

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:

  1. On your device, open Settings > About phone and tap Build number vii times.
  2. Render to the previous screen (Settings). Developer options appears at the bottom of the list. Tap Developer options.
  3. Enable USB Debugging.

Now you can connect your device and run the app from Android Studio.

  1. 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.
  2. In Android Studio, click Run 609c3e4473493202.png 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.
  3. 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:

  1. Disconnect your device from your evolution machine and reconnect it.
  2. Restart Android Studio.

If your computer yet does not discover the device or declares information technology "unauthorized":

  1. Disconnect the device.
  2. On the device, open Settings->Developer Options.
  3. Tap Revoke USB Debugging authorizations.
  4. Reconnect the device to your computer.
  5. 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. 791b06443568c703.png 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.

24ebb1f42e1fb418.png

At the acme right of the screen, at that place's a menu with 3 vertical dots. 37010a0e7f96362c.png 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. 1fc9e57692132430.png

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

  1. Find and open the layout folder (app > res > layout) on the left side in the Project console. bb7b4fe5af80859d.png
  2. 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. cb9d2ce821f0a8b.png

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.

  1. In the upper right corner of the Blueprint editor, above Attributes (4), find the three icons that wait like this: c60f285cb7fbc306.png These represent Code (lawmaking only), Dissever (code + design), and Design (design only) views.
  2. 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: 32d3075ed7f5c02c.png

  1. 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.

a7d0a08766682f9.png

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.

  1. 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. 6572c0c05460eafd.png

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.

  1. 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. c40138d924cedb8f.png
  2. Use the device carte to view the layout on different devices. (This is extremely useful for testing!)

46754977c9c3d6c9.png

On the correct is the Attributes panel. You'll acquire about that later on.

Step 2: Explore and resize the Component Tree

  1. 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.

855789e5c4867c8f.png

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. 7b183024169396dd.png

The Component Tree closes. 4. Bring back the Component Tree by clicking the vertical label Component Tree on the left.

35c14a27fd2ce30a.png

Step 3: Explore view hierarchies

  1. In the Component Tree, discover that the root of the view hierarchy is a ConstraintLayout view.

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.

506cf77387f00782.png

  1. If the code isn't showing, switch to Code or Split up view using the icons in the upper right corner.
  2. 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

  1. In the lawmaking editor, examine the properties in the TextView element.
                        <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Hello starting time fragment"    ... />                                              
  1. 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"                                              
  1. 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>                                              
  1. Change the value of the cord property to Hello World!.
  2. Switch back to fragment_first.xml.
  3. Select textview_first in the Component Tree. 19cfd9f54f58b379.png
  4. Look at the Attributes panel on the correct, and open the Alleged Attributes section if needed. 549f087103c9acbe.png
  1. In the text field of the TextView in 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. 8bb6bf0caffa82a4.png
  1. Run the app to run into the modify you lot fabricated in strings.xml. Your app now shows "Hello World!".

d2103406630c3527.png

Step 5: Modify text display backdrop

  1. With textview_first all 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.)

37c72a9385dab52d.png

  1. 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.)
  2. 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.

39597ff5cf9661da.png

  1. Select @android:color/darker_gray and press Enter.

Below is an instance of the textAppearance attributes afterward making some changes.

8751426a21281f94.png

  1. 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"                                              
  1. Run your app again and run across the changes practical to your Hi World! string

c715d9230068d0f8.png

Footstep six: Display all attributes

  1. In the Attributes panel, curl downward until you find All Attributes.

6e28336e8d85fa14.png

  1. 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.

  1. In the Project console on the left, double-click on res > values > colors.xml to open the color resource file.

8fa53d358e4a9813.png

                        <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.

  1. Become dorsum to fragment_first.xml so you tin see the XML code for the layout.
  2. Add a new belongings to the TextView called android:groundwork, and start typing to ready its value to @color. Y'all can add this property anywhere within the TextView code.

A menu pops upward offering the predefined color resources:

f08dbc2b6d4fc39.png

  1. Choose @color/colorPrimaryDark.
  2. Change the property android:textColor and 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.

c0c2141dd09c7ea7.png

Step 2: Add together a new color to utilize as the screen background color

  1. Back in colors.xml, create a new color resources called screenBackground:
                        <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.

e2749d2e88ddf4a3.png

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.

  1. Become back to fragment_first.xml.
  2. In the Component Tree, select the ConstraintLayout. 98c54173559bb461.png
  3. In the Attributes panel, select the background property and printing Enter. Blazon "c" in the field that appears.
  4. In the menu of colors that appears, select @color/screenBackground. Press Enter to complete the selection.

4ad182142b7286e6.png

  1. Click on the yellow patch to the left of the color value in the background field.

825da5a9b24ce5ff.png

It shows a listing of colors defined in colors.xml. Click the Custom tab to choose a custom colour with an interactive color chooser. ebd2ec170406402a.png

  1. Feel free to change the value of the screenBackground color, merely make sure that the concluding color is noticeably unlike from the colorPrimary and colorPrimaryDark colors.

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.

  1. In fragment_first.xml, in the Component Tree, select the ConstraintLayout.

3b78c455704d36b8.png

  1. In the Attributes console, find and aggrandize the Layout department. ef495439c2df9fac.png

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.

  1. Notice that the entire groundwork of the screen uses the screenBackground color.

6cda01dc20388d55.png

  1. 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)
  2. 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.

b8740b4dc43dc9c4.png

  1. 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.
  2. Fix both the width and meridian of the TextView and the Push dorsum 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.

94e4cf7f4bb5264b.png

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

  1. In fragment_first.xml, expect at the constraint backdrop for the TextView.
                        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.

  1. Select textview_first in the Component Tree and await at the Constraint Widget in the Attributes panel.

938d3a1c319e1f.png

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. 7d73d3d74c8ebbb9.png

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.

  1. 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.

47603a2d993c378b.png

  1. Click on some of the categories, and scroll the listed items if needed to get an idea of what's available.
  2. Select Button, which is near the top, and drag and driblet it onto the blueprint view, placing information technology underneath the TextView near the other button.

91ddff47af3cde61.png

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.

  1. Motion the cursor over the circumvolve at the top of the Button.

d692d553fdb8d06c.png

  1. Click and drag the circle at the acme of the Push onto the circle at the bottom of the TextView.

9e7bcb556cd2b58c.png

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.

7aa4fd347b3ebde9.png

  1. 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.
  2. 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"                                              
  1. 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.
  2. 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.

  1. Click on the button you just added in the design layout.
  2. Look at the Attributes panel on the right, and discover the id field.
  3. Alter the id from push to toast_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 Ctrl key (Command on a Mac) and movement the cursor over the circle for the constraint until the circle highlights, then click the circle. 1f8c250ad15873d5.png
  • 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.

7f4931356c145bab.png

If you delete a constraint and want it back, either undo the activity, or create a new constraint.

Pace five: Delete the chain constraints

  1. Click on the Adjacent button, and then delete the constraint from the meridian of the button to the TextView.
  2. 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

  1. Constrain the correct side of the Next button to the correct of the screen if it isn't already.
  2. Delete the constraint on the left side of the Adjacent button.
  3. 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 TextView and 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.
  4. Also constrain the TextView to 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.

7fb69c02100a87f6.png

  1. In the fragment_first.xml layout file, find the text belongings for the toast_button button.
                        <Button    android:id="@+id/toast_button"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Button"                                              
  1. Notice that the text "Button" is directly in the layout field, instead of referencing a string resource equally the TextView does. This will make it harder to translate your app to other languages.
  2. To fix this, click the highlighted lawmaking. A light bulb appears on the left.

47544075e3e5ecdb.png

  1. Click the lightbulb. In the menu that pops up, select Extract string resource. ca47cfeb06a1602.png
  2. In the dialog box that appears, change the resource name to toast_button_text and the resource value to Toast and click OK.

8fa866598929c1b4.png

  1. Detect that the value of the android:text property 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"                                              
  1. 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>                                              
  1. Run the app to brand certain it displays as you look information technology to.

73c7729f2d8329df.png

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.

  1. As you did for the Toast push, change the id of the Next button from button_first to random_button in the Attributes panel.
  2. 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. 434e77fabe53b6a3.png
  3. In strings.xml, right-click on the side by side string resources.
  4. Select Refactor > Rename... and alter the name to random_button_text.
  5. Click Refactor to rename your string and close the dialog.
  6. Change the value of the string from Side by side to Random.
  7. If you desire, movement random_button_text to below toast_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.

7e6529faadd88569.png

  1. In fragment_first.xml, add another button to the layout, and drop it somewhere between the Toast button and the Random push, beneath the TextView.
  2. 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.
  3. 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:

7588895a67295422.png

  1. Examine the XML code for fragment_first.xml. Do whatever of the buttons have the attribute app: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.

  1. Change the text of the TextView to prove 0 (the number zero).
  2. Change the id of the last button you added, button2, to count_button in the Attributes panel in the design editor.
  3. In the XML, extract the string resource to count_button_text and set the value to Count.
  4. bbe0bcab6903ea27.png

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

  1. Run the app.

Step xi: Fix errors if necessary

c01516073934ed58.png

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

  1. In colors.xml, change the value of screenBackground to #2196F3, which is a blue shade in the Material Design palette.
  2. 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

  1. In the layout, add a background color to each of the buttons. (You can either edit the XML in fragment_first.xml or use the Attributes console, whichever you prefer.)
                        android:background="@color/buttonBackground"                                              

Step iii: Alter the margins of the left and right buttons

  1. 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. 81c294a2cf04b801.png

Footstep 4: Update the advent of the TextView

  1. Remove the groundwork color of the TextView, either by clearing the value in the Attributes panel or by removing the android:background attribute 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"                                              
  1. Change the font-family of the TextView to sans-serif (if it'south not already).
  2. Add an app:layout_constraintVertical_bias property to the TextView, 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"                                              
  1. 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. 7c73e04dc2f35d00.png
  1. 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.

214cfb8299ed8d36.png

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.

  1. In Android Studio, open up the settings editor by going to File > Other Settings > Preferences for New Projects.
  2. Select Automobile Imports. In the Coffee department, make certain Add together Unambiguous Imports on the wing is checked.

5507aa63b0db10d5.png 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.

b3d6daf5bb6784d9.png

  1. 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.)
  1. 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();    } });                                              
  1. Run the app and press the Toast button. Do you see the toasty bulletin at the lesser of the screen? b3d6daf5bb6784d9.png
  2. 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.

  1. In the fragment_first.xml layout file, detect the id for the TextView:
                        <TextView    android:id="@+id/textview_first"                                              
  1. In FirstFragment.java, add a click listener for the count_button below the other click listeners in onViewCreated(). 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);    } });                                              
  1. In the FirstFragment form, add the method countMe() that takes a unmarried View argument. This method volition be invoked when the Count button is clicked and the click listener chosen.
                        private void countMe(View view) {    }                                              
  1. 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();                                              
  1. Convert the value to a number, and increment information technology.
                                                  ...     // Convert value to a number and increase it     Integer count = Integer.parseInt(countString);     count++;                                              
  1. Display the new value in the TextView by programmatically setting the text property of the TextView.
                                                  ...    // 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.

  1. In the FirstFragment class before any methods, add a fellow member variable for showCountTextView of type TextView.
                        TextView showCountTextView;                                              
  1. In onCreateView(), you will call findViewById() to get the TextView that shows the count. The findViewById() method must exist chosen on a View where 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);                                              
  1. Call findViewById() on fragmentFirstLayout, and specify the id of the view to find, textview_first. Cache that value in showCountTextView.
                                                  ...     // Get the count text view     showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);                                              
  1. Return fragmentFirstLayout from onCreateView().
                        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; }                                              
  1. Run your app. Press the Count push button and watch the count update.

f2b19b9209cad4f4.png

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.

c7029fe48ec2a802.png

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: a991c2db96dcafb3.png 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

  1. Open fragment_second.xml (app > res > layout > fragment_second.xml) and switch to Blueprint View if needed. Discover that information technology has a ConstraintLayout that contains a TextView and a Push button.
  2. Remove the chain constraints between the TextView and the Push. e49352faab20c765.png
  3. Add another TextView from the palette and driblet information technology well-nigh the middle of the screen. This TextView volition exist used to display a random number between 0 and the current count from the commencement Fragment.
  4. Ready the id to @+id/textview_random (textview_random in the Attributes panel.)
  5. Constrain the superlative edge of the new TextView to the bottom of the first TextView, 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.
  6. Set both width and height to wrap_content.
  7. Set the textColor to @android:color/white, set the textSize to 72sp, and the textStyle to bold.

81dc7122e9ddaea1.png

  1. Set the text to "R". This text is just a placeholder until the random number is generated.
  2. 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" />                                              
  1. In fragment_second.xml, select textview_second, which currently has the text "How-do-you-do second fragment. Arg: %ane$s" in the hello_second_fragment string resource.
  2. If android:text isn't set, ready it to the hello_second_fragment string resources.
                        android:text="@string/hello_second_fragment"                                              
  1. Alter the id to textview_header in the Attributes panel.
  2. 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.
  3. 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.
  4. Remove whatsoever bottom constraint.
  5. Ready the text color to @color/colorPrimaryDark and the text size to 24sp.
  6. In strings.xml, change hello_second_fragment to "Here is a random number between 0 and %d."
  7. Use Refactor > Rename... to change the proper name of hello_second_fragment to random_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" />                                              

ff7f9969afbd67ff.png

Footstep three: Change the background color of the layout

Requite your new activity a different background color than the showtime activity:

  1. In colors.xml, add a new colour resource:
                        <colour name="screenBackground2">#26C6DA</color>                                              
  1. In the layout for the second activeness, fragment_second.xml, set the background of the ConstraintLayout to the new colour.

In the Attributes panel:

9948b482fb81ef5.png

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.

  1. 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.

  1. You can freely move the elements in the navigation editor. For case, if the fragments appear with SecondFragment to the left, drag FirstFragment to the left of SecondFragment and so they appear in the lodge you work with them.

504c2156d46d4d6b.png

Step 5: Enable SafeArgs

This volition enable SafeArgs in Android Studio.

  1. Open Gradle Scripts > build.gradle (Project: My Outset App)
  2. Find the dependencies section In the buildscript section, and add the following lines after the other classpath entries:
                        def nav_version = "2.3.0-alpha04" classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"                                              
  1. Open Gradle Scripts > build.gradle (Module: app)
  2. Just below the other lines that begin with apply plugin add a line to enable SafeArgs:
                        apply plugin: 'androidx.navigation.safeargs'                                              
  1. Android Studio should brandish a message about the Gradle files existence changed. Click Sync Now on the right hand side. 50cedf1769381459.png

After a few moments, Android Studio should display a bulletin in the Sync tab that it was successful: a1c51cb92c04e07e.png

  1. 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

  1. 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.)
  2. In the Actions section, it shows what activeness will happen for navigation, namely going to SecondFragment.
  3. Click on SecondFragment, and await at the Attributes panel.

The Arguments section shows Nix to show.

  1. Click on the + in the Arguments section.
  2. In the Add Argument dialog, enter myArg for the name and set the type to Integer, then click the Add button. c334d61be24eb01d.png

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.

  1. Open FirstFragment.java (app > coffee > com.example.myfirstapp > FirstFragment)
  2. Find the method onViewCreated() and notice the code that sets up the click listener to become from the first fragment to the second.
  3. 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());                                              
  1. Create an action with currentCount as the argument to actionFirstFragmentToSecondFragment().
                        FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount);                                              
  1. 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);        }    }); }                                              
  1. 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.

  1. In SecondFragment.java, add an import for navArgs to the list of imported libraries.
                        import androidx.navigation.fragment.navArgs;                                              
  1. In the onViewCreated() method below the line that starts with super, 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);                                              
  1. 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); }                                              
  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());                                              
  1. 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? 6cba94311109e72f.png

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.