HOW TO BUILD A MOBILE APP WITH ANDROID STUDIO

Mobile app

What is Android studio?

Android Studio is the official Integrated Development Environment (IDE) for Android app development, based on IntelliJ IDEA . … A unified environment where you can develop for all Android devices. Apply Changes to push code and resource changes to your running app without restarting your app.

FEATURES OF ANDROID STUDION

Code and iterate faster than ever 

Based on Intellij IDEA, Android Studio provides the fastest possible turnaround on your coding and running workflow.The following are its features.

Apply changes

Android Studio’s Apply Changes feature lets you push code and resource changes to your running app without restarting your app—and, in some cases, without restarting the current activity. This flexibility helps you control how much of your app is restarted when you want to deploy and test small, incremental changes while preserving your device’s current state.

To work through this codelab, you will need a computer that can run Android studio 3.6or higher (or already has Android Studio 3.6 or higher installed).

Intelligent code editor

The code editor helps you write better code, work faster, and be more productive by offering advanced code completion, refactoring, and code analysis. As you type, Android Studio provides suggestions in a dropdown list. Simply press Tab to insert the code.

Fast and feature rich emulator

The Android Emulator installs and starts your apps faster than a real device and allows you to prototype and test your app on various Android device configurations: phones, tablets, Android Wear, and Android TV devices. You can also simulate a variety of hardware features such as GPS location, network latency, motion sensors, and multi-touch input.

Code with confidence 

At every step, Android Studio helps ensure that you’re creating the best code possible.

Code templates and sample apps

Android Studio includes project and code templates that make it easy to add well-established patterns such as a navigation drawer and view pager. You can start with a code template or even right-click an API in the editor and select Find Sample Code to search for examples. Moreover, you can import fully functional apps from GitHub, right from the Create Project screen.

Lintelligence

Android Studio provides a robust static analysis framework and includes over 365 different lint checks across the entirety of your app. Additionally, it provides several quick fixes that help you address issues in various categories, such as performance, security, and correctness, with a single click.

Testing tools and frameworks

Android Studio provides extensive tools to help you test your Android apps with JUnit 4 and functional UI test frameworks. With Espresso Test Recorder, you can generate UI test code by recording your interactions with the app on a device or emulator. You can run your tests on a device, an emulator, a continuous integration environment, or in Firebase test lab

Configure builds without limits 

Android Studio’s project structure and Gradle-based builds provide the flexibility you need to generate APKs for all device types.

Robust and flexible build system

Android Studio offers build automation, dependency management, and customizable build configurations. You can configure your project to include local and hosted libraries, and define build variants that include different code and resources, and apply different code shrinking and app signing configurations.

Designed for teams

Android Studio integrates with version control tools, such as GitHub and Subversion, so you can keep your team in sync with project and build changes. The open source Gradle build system allows you to tailor the build to your environment and run on a continuous integration server such as Jenkins.

Optimized for all android devices

Android Studio provides a unified environment where you can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Structured code modules allow you to divide your project into units of functionality that you can independently build, test, and debug.

Create rich and connected apps 

Android Studio knows not all code is written in Java and not all code runs on the user’s device.

C++ and NDK Support

Android Studio fully supports editing C/C++ project files so you can quickly build JNI components in your app. The IDE provides syntax highlighting and refactoring for C/C++, and an LLDB-based debugger that allows you to simultaneously debug your Java and C/C++ code. The build tools can also execute your CMake and ndk-build scripts without any modification and then add the shared objects to your APK.

Firebase and cloud integration

The Firebase Assistant helps you connect your app to Firebase and add services such as Analytics, Authentication, Notifications and more with step-by-step procedures right inside Android Studio. Built-in tools for Google cloud platformalso help you integrate your Android app with services such as Google Cloud Endpoints and project modules specially-designed for Google App Engine.

Eliminate tiresome tasks 

Android Studio provides GUI tools that simplify the less interesting parts of app development.

Layout editor

When working with XML layout files, Android Studio provides a drag-and-drop visual editor that makes it easier than ever to create a new layout. The Layout Editor was built in unison with the ConstraintLayout API, so you can quickly build a layout that adapts to different screen sizes by dragging views into place and then adding layout constraints with just a few clicks.

APK Analyzer

You can use the APK Analyzer to easily inspect the contents of your APK. It reveals the size of each component so you can identify ways to reduce the overall APK size. It also allows you to preview packaged assets, inspect the DEX files to troubleshoot multidex issues, and compare the differences between two APKs.

Vector asset studio

Android Studio makes it easy to create a new image asset for every density size. With Vector Asset Studio, you can select from Google-provided material design icons or import an SVG or PSD file. Vector Asset Studio can also generate bitmap files for each screen density to support older versions of Android that don’t support the Android vector drawable format.

Translations editor

The Translations Editor gives you a single view of all of your translated resources, making it easy to change or add translations, and to find missing translations without opening each version of the strings.xml file. It even provides a link to order translation services.

STEPS TO BUILDING AN APP WITH ANDROID STUDIO

1. Welcome!

6cba94311109e72f.png

In this codelab, you’ll learn how to build and run your first Android app in the Java programming language.

What you must know already

This codelab is written for programmers and assumes that you know either the Java or Kotlin programming language. If you are an experienced programmer and adept at reading code, you will likely be able to follow this codelab, even if you don’t have much experience with Java.

What you’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 display a second screen when a button is pressed.

Use Android Studio and Java to write Android apps

You write Android apps in the Java programming language using an IDE called Android Studio. Based on JetBrains’ IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android development.

Note: This version of the codelab requires Android Studio 3.6 or higher.

To work through this codelab, you will need a computer that can run Android studio 3.6or higher (or already has Android Studio 3.6 or higher installed).

2. Install Android Studio

Note: This version of the codelab requires Android Studio 3.6 or higher.

You can download Android Studio 3.6 from the Android Studio page.

Android Studio provides a complete IDE, including an advanced code editor and app templates. It also contains tools for development, debugging, testing, and performance that make it faster and easier to develop apps. You can use Android Studio to test your apps with a large range of preconfigured emulators, or on your own mobile device. You can also build production apps and publish apps on the Google Play store.

Note: Android Studio is continually being improved. For the latest information on system requirements and installation instructions, see the Android studio download page

Android Studio is available for computers running Windows or Linux, and for Macs running macOS. The OpenJDK (Java Development 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. Accept the default configurations for all steps, and ensure that all components are selected for installation.
  3. After the install is complete, the setup wizard 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 step, you will create a new Android project for your first app. This simple app displays the string “Hello World” on the screen of an Android virtual or physical device.

Here’s what the finished app will look like:

72c7e6d2960f4faa.png

What you’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 own physical device, if you have one.

Step 1: Create a new project

  1. Open Android Studio.
  2. In the Welcome to Android Studio dialog, click Start a new Android Studio projectc7c8a5cc4c9029b.png
  3. Select Basic Activity (not the default). Click Next73e63b490a2f4ae6.png
  4. Give your application a name such as My First App.
  5. Make sure the Language is set to Java3ffb3ca42472b4f6.png
  6. Leave the defaults for the other fields.
  7. Click Finish.

After these steps, Android Studio:

  • Creates a folder for your Android Studio project called MyFirstApp. This is usually in a folder called AndroidStudioProjects below your home directory.
  • Builds your project (this may take a few moments). Android Studio uses Gradle as its build system. You 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 set up

When your project first opens in Android Studio, there may be a lot of windows and panes open. To make it easier to get 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 point, your screen should look a bit less cluttered, similar to the screenshot shown below.

70183da1f878e11a.png

Step 3: Explore the project 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 up 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 see the file hierarchy, choose the Project files view by clicking (3).)

  1. Double-click the app (1) folder to expand the hierarchy of app files. (See (1) in the screenshot.)
  2. If you click Project (2), you can hide or show the Project view. You might need to select View > Tool Windows to see this option.
  3. The current Project view selection (3) is Project > Android.

In the Project > Android view you see three or four top-level folders below your app folder: manifestsjavajava (generated) and res. You 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. 2. Expand the **java** folder. All your Java language files are organized here. The **java** folder contains three subfolders:

com.example.myfirstapp: This folder contains the Java source code files for your app.

com.example.myfirstapp (androidTest): This folder is where you would put your instrumented tests, which are tests that run on an Android device. It starts out with a skeleton test file.

com.example.myfirstapp (test): This folder is where you 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 activity that has a layout file called activity_main.xml. It also contains content_main.xmlfragment_first.xml, and fragment_second.xml.

menu: This folder contains XML files describing any 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 resources, such as strings and colors, used in your app.

Step 4: Create a virtual device (emulator)

In this task, you will use the Android virtual device AVD Manager to create a virtual device (or emulator) that simulates the configuration for a particular type of Android device.

The first step is to create a configuration that describes the virtual device.

  1. In Android Studio, select Tools > AVD Manager, or click the AVD Manager icon in the toolbar. 1ef215721ed1bd47.png
  2. Click +Create Virtual Device. (If you have created a virtual device before, 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. Choose a device definition, such as Pixel 2, and click Next. (For this codelab, it really 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 next to a latest release, it is not installed yet, and you need to download it first. If necessary, click the link to start the download, and click Next when it’s done. This may take a while depending on your connection speed.

Note: System images can take up a large amount of disk space, so just download what you need.

  1. In the next dialog box, accept the defaults, and click Finish.

The AVD Manager now shows the virtual device you added.

  1. If the Your Virtual Devices AVD Manager window is still open, go ahead and close it.

Step 5: 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

If you get a dialog box stating “Instant Run requires that the platform corresponding to your target device (Android N…) is installed” go ahead and click Install and continue.

  1. In Run > Select Device, under Available devices, select the virtual device that you just configured. This menu also appears in the toolbar.
b1215d5cf034b077.png

The emulator starts and boots just like a physical device. Depending on the speed of your computer, this may take a while. You can look in the small horizontal status bar at the very bottom of Android Studio for messages to see the progress.

Messages that might appear briefly in the status bar
Gradle build runningd0619795547e4c14
Waiting for target device to come on line9f8985362a878fea
Installing APK2126fe0fde82e5cb
Launching activityda65b2c9371666d0

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 as shown in the following screenshot.

89960f5a856e1aa7.png

Note: It is a good practice to start the emulator at the beginning of your session. Don’t close the emulator until you are done testing your app, so that you don’t have to wait for the emulator to boot again. Also, don’t have more than one emulator running at once, to reduce memory usage.

Step 6: Run your app on a device (if you have one)

What you need:

  • An Android device such as a phone or tablet.
  • A data cable to connect your Android device to your computer via the USB port.
  • If you 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 hard ware device documentation. On Windows, you 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, you must turn on USB Debugging on your Android device.

On Android 4.2 and higher, the Developer options screen is hidden by default. To show Developer options and enable USB Debugging:

  1. On your device, open Settings > About phone and tap Build number seven times.
  2. Return 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 machine with a USB cable. On the device, you might need to agree to allow USB debugging from your development device.
  2. In Android Studio, click Run 609c3e4473493202.png in the toolbar at the top of the window. (You might need to select View > Toolbar to see this option.) 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 it.

Note: If your device is running an Android platform that isn’t installed in Android Studio, you might see a message asking if you want to install the needed platform. Click Install and Continue, then click Finish when the process is complete.

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 development machine and reconnect it.
  2. Restart Android Studio.

If your computer still does not find the device or declares it “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 driver for your device.

Step 7: Explore the app template

When you created the project and selected Basic Activity, Android Studio set up a number of files, folders, and also user interface elements for you, so you can start 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 addition to the Next button, notice the floating action button with an email icon. 791b06443568c703.png If you tap that button, you’ll see it has been set up to briefly show a message at the bottom of the screen. This message space is called a snackbar, and it’s one of several ways to notify users of your app with brief information.

24ebb1f42e1fb418.png

At the top right of the screen, there’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 menu with a Settings item. Choosing Settings doesn’t do anything yet, but having it set up for you makes it easier to add user-configurable settings to your app. 1fc9e57692132430.png

Later in this codelab, you’ll look at the Next button and modify the way it looks and what it does.

4. Task: Explore the layout editor

Generally, each screen in your Android app is associated with one or more fragments. The single screen displaying “Hello first fragment” is created by one fragment, called FirstFragment. This was generated for you when you created your new project. 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 you 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 task, you will explore some of the panels in the layout editor, and you will learn how to change property of views.

What you’ll learn

  • How to use the layout editor.
  • How to set property values.
  • How to add string resources.
  • How to add color resources.

Step 1: Open the layout editor

  1. Find and open the layout folder (app > res > layout) on the left side in the Project panel. bb7b4fe5af80859d.png
  2. Double-click fragment_first.xml.

Troubleshooting: If you don’t see the file fragment_first.xml, confirm you are running Android Studio 3.6 or later, which is required for this codelab.

The panels to the right of the Project view comprise the Layout Editor. They may be arranged differently in your version of Android Studio, but the function is the same. cb9d2ce821f0a8b.png

On the left is a Palette (1) of views you 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 Design editor, above Attributes (4), find the three icons that look like this: c60f285cb7fbc306.png These represent Code (code only), Split (code + design), and Design (design only) views.
  2. Try selecting the different modes. Depending on your screen size and work style, you may prefer switching between Code and Design, or staying in Split view. If your Component Tree disappears, hide 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. Use these buttons to adjust the size of what you see, or click the zoom-to-fit button 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 menu in the top left of the design toolbar to display the design view, the blueprint view, and both views side by side. 6572c0c05460eafd.png

Depending on the size of your screen and your preference, you may wish to only show the Design view or the Blueprint view, instead of both.

  1. Use the orientation icon to change the orientation of the layout. This allows you to test how your layout will fit portrait and landscape modes. c40138d924cedb8f.png
  2. Use the device menu to view the layout on different devices. (This is extremely useful for testing!)
46754977c9c3d6c9.png

On the right is the Attributes panel. You’ll learn about that later.

Step 2: Explore and resize the Component Tree

  1. In fragment_first.xml, look at the Component Tree. If it’s 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 so you can read at least part of the strings. 3. Click the Hide icon at the top right of the Component Tree7b183024169396dd.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, notice 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 one example of a view group. 2. Notice that the ConstraintLayout contains a TextView, called textview_first and a Button, called button_first.

506cf77387f00782.png
  1. If the code isn’t showing, switch to Code or Split view using the icons in the upper right corner.
  2. In the XML code, notice that the root element is <androidx.constraintlayout.widget.ConstraintLayout>. The root element contains a <TextView> element and a <Button> element.
<androidx.constraintlayout.widget.ConstraintLayout
  ... >

   <TextView
      ...  />

   <Button
      ...  />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Change property values

  1. In the code editor, examine the properties in the TextView element.
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Hello first fragment"
   ... />
  1. Click on the string in the text property, and you’ll notice it refers to a string resource, hello_first_fragment.
android:text="@string/hello_first_fragment"
  1. Right-click on the property and click Go To > Declaration or Usages

values/strings.xml opens with the string highlighted.

<string name="hello_first_fragment">Hello first fragment</string>
  1. Change the value of the string property to Hello World!.
  2. Switch back to fragment_first.xml.
  3. Select textview_first in the Component Tree19cfd9f54f58b379.png
  4. Look at the Attributes panel on the right, and open the Declared Attributes section if needed. 549f087103c9acbe.png

Troubleshooting this step:

  • If the Attributes panel is not visible, click the vertical Attributes label at the top right. e6a2a689769c8afd.png
  1. In the text field of the TextView in Attributes, notice it still refers to the string resource @string/hello_first_fragment. Having the strings in a resource 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, because your translators don’t have to know anything about the app code. 8bb6bf0caffa82a4.png

Tip: To find a property in the list of all the properties, click on the magnifying glass icon to the right of Attributes, and begin typing the name of the property. Android Studio will show just the properties that contain that string.

6349e6a522fda9ea.png
1e116f4ea013be17.png
  1. Run the app to see the change you made in strings.xml. Your app now shows “Hello World!”.
d2103406630c3527.png

Step 5: Change text display properties

  1. With textview_first still selected in the Component Tree, in the layout editor, in the list of attributes, under Common Attributes, expand the textAppearance field. (You may need to scroll down to find it.)
37c72a9385dab52d.png
  1. Change some of the text appearance properties. For example, change the font family, increase the text size, and select bold style. (You might need to scroll the panel to see all the fields.)
  2. Change the text color. Click in the textColor field, and enter g.

A menu pops up 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 example of the textAppearance attributes after making some changes.

8751426a21281f94.png
  1. Look at the XML for the TextView. You see that the new properties 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:color/darker_gray"
   android:textSize="30sp"
   android:textStyle="bold"
  1. Run your app again and see the changes applied to your Hello World! string
c715d9230068d0f8.png

Step 6: Display all attributes

  1. In the Attributes panel, scroll down until you find All Attributes.

If you don’t see any attributes in the Attributes panel, make sure textview_first is still selected in the Component Tree.

6e28336e8d85fa14.png
  1. Scroll through the list to get an idea of the attributes you could set for a TextView.

5. Task: Add color resources

So far you have learned how to change property values. Next, you will learn how to create more resources like the string resources you worked with earlier. Using resources enables you to use the same values in multiple places, or to define values and have the UI update automatically whenever the value is changed.

What you’ll learn

  • How resources are defined.
  • Adding and using color resources.
  • The results of changing layout height and width.

Step 1: Add color resources

First, you’ll learn how to add new color resources.

  1. In the Project panel on the left, double-click on res > values > colors.xml to open the color resource file.
8fa53d358e4a9813.png
<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
</resources>

The colors.xml file opens in the editor. So far, three colors have been defined. These are the colors you can see in your app layout, for example, purple for the app bar.

Note: Different versions of Android Studio use different values for these colors, so you may see other colors here.

  1. Go back to fragment_first.xml so you can see the XML code for the layout.
  2. Add a new property to the TextView called android:background, and start typing to set its value to @color. You can add this property anywhere inside the TextView code.

A menu pops up offering the predefined color resources:

f08dbc2b6d4fc39.png
  1. Choose @color/colorPrimaryDark.
  2. Change the property android:textColor and give 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 a new color to use as the screen background color

  1. Back in colors.xml, create a new color resource called screenBackground:
<color name="screenBackground">#FFEE58</color>

Color can be defined as 3 hexadecimal numbers (#00-#FF, or 0-255) representing the red, blue, and green (RGB) components. The color you just added is yellow. Notice that the colors corresponding to the code are displayed in the left margin of the editor.

e2749d2e88ddf4a3.png

Note 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 example, #88FFEE58 makes the color semi-transparent, and if you use #00FFEE58, it’s fully transparent and disappears from the left-hand bar.

  1. Go back to fragment_first.xml.
  2. In the Component Tree, select the ConstraintLayout98c54173559bb461.png
  3. In the Attributes panel, select the background property and press Enter. Type “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 list of colors defined in colors.xml. Click the Custom tab to choose a custom color with an interactive color chooser. ebd2ec170406402a.png

  1. Feel free to change the value of the screenBackground color, but make sure that the final color is noticeably different from the colorPrimary and colorPrimaryDark colors.

Step 3: Explore width and height properties

Now that you have a new screen background color, you will use it to explore the effects of changing the width and height properties of views.

  1. In fragment_first.xml, in the Component Tree, select the ConstraintLayout.
3b78c455704d36b8.png
  1. In the Attributes panel, find and expand the Layout section. 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 effectively the size of your screen.

Tip: All views must have layout_width and layout_height properties.

  1. Notice that the entire background of the screen uses the screenBackground color.
6cda01dc20388d55.png
  1. Select textview_first. Currently the layout width and height are wrap_content, which tells the view to be just big enough to enclose its content (plus padding)
  2. Change both the layout width and layout height to match_constraint, which tells the view to be as big as whatever it’s 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 button. The button and the text view are at the same level in the view hierarchy inside the constraint layout, 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 also change the width and height of the button_first.
  2. Set both the width and height of the TextView and the Button back to wrap_content.

6. Task: Add views and constraints

In this task, you will add two more buttons to your user interface, and update the existing button, as shown below.

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.

Step 1: View constraint properties

  1. In fragment_first.xml, look at the constraint properties 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 carefully.

You can constrain the top, bottom, left, and right of a view to the top, bottom, left, and right of other views.

  1. Select textview_first in the Component Tree and look at the Constraint Widget in the Attributes panel.
938d3a1c319e1f.png

The square represents the selected view. Each of the grey dots represents a constraint, to the top, bottom, left, and right; for this example, from the TextView to its parent, the ConstraintLayout, or to the Next button for the bottom constraint. 3. Notice that the blueprint and design views also show the constraints when a particular view is selected. Some of the constraints are jagged lines, but the one to the Next button is a squiggle, because it’s a little different. You’ll learn more about that in a bit. 7d73d3d74c8ebbb9.png

Step 2: Add buttons and constrain their positions

To learn how to use constraints to connect the positions of views to each other, you will add buttons to the layout. Your first goal is to add a button and some constraints, and change the constraints on the Next button.

  1. Notice the Palette at the top left of the layout editor. Move the sides if you need to, so that you can see 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 drop it onto the design view, placing it underneath the TextView near the other button.
91ddff47af3cde61.png

Notice that a Button 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 button to the bottom of the TextView.

  1. Move the cursor over the circle at the top of the Button.
d692d553fdb8d06c.png
  1. Click and drag the circle at the top of the Button onto the circle at the bottom of the TextView.
9e7bcb556cd2b58c.png

The Button moves up to sit just below the TextView because the top of the 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 panel. It shows some constraints for the Button, including Top -> BottomOf textView.
  2. Take a look at the XML code for the button. It now includes the attribute that constrains the top of the button to the bottom of the TextView.
app:layout_constraintTop_toBottomOf="@+id/textview_first"
  1. You may see a warning, “Not Horizontally Constrained“. To fix this, add a constraint from the left side of the button to the left side of the screen.
  2. Also add a constraint to constrain the bottom of the button to the bottom of the screen.

Before adding another button, relabel this button so things are a little 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 notice the id field.
  3. Change the id from button to toast_button.

Step 4: Adjust the Next button

You will adjust the button labeled Next, which Android Studio created for you when you created the project. The constraint between it and the TextView looks a little different, a wavy line instead of a jagged one, 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 now, you’ll delete the chained constraints and replace them with regular constraints.

To delete a constraint:

  • In the design view or blueprint view, hold the Ctrl key (Command on a Mac) and move 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 it shows an x, then click it.
7f4931356c145bab.png

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

Step 5: Delete the chain constraints

  1. Click on the Next button, and then delete the constraint from the top of the button to the TextView.
  2. Click on the TextView, and then delete the constraint from the bottom of the text to the Next button.

Step 6: Add new constraints

  1. Constrain the right side of the Next button to the right of the screen if it isn’t already.
  2. Delete the constraint on the left side of the Next button.
  3. Now constrain the top and bottom of the Next button so that the top of the button is constrained to the bottom of the TextView and the bottom is constrained to the bottom 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 like the views are jumping around a lot, but that’s normal as you add and remove constraints.

Your layout should now look something like this.

7fb69c02100a87f6.png

Step 7: Extract string resources

  1. In the fragment_first.xml layout file, find the text property 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 as the TextView does. This will make it harder to translate your app to other languages.
  2. To fix this, click the highlighted code. A light bulb appears on the left.
47544075e3e5ecdb.png
  1. Click the lightbulb. In the menu that pops up, select Extract string resourceca47cfeb06a1602.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. Notice 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. Go to the res > values > strings.xml file. Notice that a new string resource has been added, named toast_button_text**.**
<resources>
   ...
   <string name="toast_button_text">Toast</string>
</resources>
  1. Run the app to make sure it displays as you expect it to.
73c7729f2d8329df.png

You now know how to create new string resources by extracting them from existing field values. (You can also add new resources to the strings.xml file manually.) And you know how to change the id of a view.

Note: The id for a view helps you identify that view distinctly from other views. You’ll use this later to find particular views using the findViewById() method in your Java code.

Step 8: Update the Next button

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 will be to generate and display a random number.

  1. As you did for the Toast button, change the id of the Next button from button_first to random_button in the Attributes panel.
  2. If you get a dialog box asking to update all usages of the button, click Yes. This will fix any other references to the button in the project code. 434e77fabe53b6a3.png
  3. In strings.xml, right-click on the next string resource.
  4. Select Refactor > Rename… and change 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 Next to Random.
  7. If you want, move random_button_text to below toast_button_text.

Step 9: Add a third button

Your final layout will have three buttons, vertically constrained the same, 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 button, below the TextView.
  2. Add vertical constraints the same as the other two buttons. Constrain the top of the third button to the bottom 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 button to the right 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 any of the buttons have the attribute app:layout_constraintVertical_bias? It’s OK if you do not see that constraint.

The “bias” constraints allows you to tweak the position of a view to be more on one side than the other when both sides are constrained in opposite directions. For example, if both the top and bottom sides of a view are constrained to the top and bottom of the screen, you can use a vertical bias to place the view more towards the top than the bottom.

Here is the XML code for the finished layout. Your layout might have different margins and perhaps some different vertical or horizontal bias constraints.The exact values of the attributes for the appearance of the TextView might be different for your app.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout <?xml version="1.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-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@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:color/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="@string/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 10: Get your UI ready for the next task

The next task is to make the buttons do something when they are pressed. First, you need to get the UI ready.

  1. Change the text of the TextView to show 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 have the following text and ids:

Buttontextid
Left buttonToast@+id/toast_button
Middle buttonCount@+id/count_button
Right buttonRandom@+id/random_button
  1. Run the app.

Step 11: Fix errors if necessary

If you edited the XML for the layout directly, you might see some errors.

c01516073934ed58.png

The errors occur because the buttons have changed their id and now these constraints are referencing non-existent views.

If you have these errors, fix them by updating the id of the buttons in the constraints that are underlined in red.

app:layout_constraintEnd_toStartOf="@+id/random_button"
app:layout_constraintStart_toEndOf="@+id/toast_button"

7. Task: Update the appearance of the buttons and the TextView

Your app’s layout is now basically complete, but its appearance can be improved with a few small changes.

Step 1: Add new color resources

  1. In colors.xml, change the value of screenBackground to #2196F3, which is a blue shade in the Material design pallete
  2. Add a new color 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 panel, whichever you prefer.)
android:background="@color/buttonBackground"

Step 3: Change the margins of the left and right buttons

  1. Give the Toast button a left (start) margin of 24dp and give the Random button a right (end) margin of 24dp. (Using start and end instead of left and right 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. Type 24 in the field and press Enter81c294a2cf04b801.png

Step 4: Update the appearance of the TextView

  1. Remove the background color of the TextView, either by clearing the value in the Attributes panel or by removing the android:background attribute from the XML code.

When you remove the background, the view background 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’s not already).
  2. Add an app:layout_constraintVertical_bias property to the TextView, to bias the position of the view upwards a little so that it is more evenly spaced vertically in the screen. Feel free to adjust the value of this constraint as you like. (Check in the design view to see how the layout looks.)
app:layout_constraintVertical_bias="0.3"
  1. You can also set the vertical bias using the Constraint Widget. Click and drag the number 50 that appears on the left side, and slide it upwards until it says 307c73e04dc2f35d00.png

Tip: Using the bias attribute instead of margins or padding results in a more pleasing layout on different screen sizes and orientations.

  • If a view is constrained to other views on both its top and bottom edges, use vertical bias to tweak its vertical position.
  • If a view is constrained on both its left and right edges, use horizontal bias to tweak its horizontal position.
  1. Make sure the layout_width is wrap_content, and the horizontal bias is 50 (app:layout_constraintHorizontal_bias="0.5" in XML).

Step 5: Run your app

If you implemented all the updates, your app will look like the following figure. If you used different colors and fonts, then your app will look a bit different.

214cfb8299ed8d36.png

8. Task: Make your app interactive

You have added buttons to your app’s main screen, but currently the buttons do nothing. In this task, you will make your buttons respond when the user presses them.

First you will make the Toast button show 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 learn

  • How to find a view by its ID.
  • How to add click listeners for a view.
  • How to set and get property values of a view from your code.

Step 1: Enable auto imports

To make your life easier, you can enable auto-imports so that Android Studio automatically imports any classes that are needed by the Java code.

  1. In Android Studio, open the settings editor by going to File > Other Settings > Preferences for New Projects.
  2. Select Auto Imports. In the Java section, make sure Add Unambiguous Imports on the fly is checked.

5507aa63b0db10d5.png 3. Close the settings editor by pressing OK.

Step 2: Show a toast

In this step, you will attach a Java method to the Toast button to show a toast when the user presses the button. A toast is a short message that appears briefly at the bottom of the screen.

b3d6daf5bb6784d9.png
  1. Open FirstFragment.java (app > java > com.example.android.myfirstapp > FirstFragment).

This class has only two methods, onCreateView() and onViewCreated(). These methods execute when the fragment starts.

As mentioned earlier, the id for a view helps you 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 Next button.

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 as an argument, then set a click listener on that view.
  • In the body of the click listener, use an action, which in this case is for navigating to another fragment, and navigate there. (You will learn about that later.)
  1. Just below that click listener, add code to set up 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(), "Hello toast!", Toast.LENGTH_SHORT);
       myToast.show();
   }
});
  1. Run the app and press the Toast button. Do you see the toasty message at the bottom of the screen? b3d6daf5bb6784d9.png
  2. If you want, extract the message string into a resource as you did for the button labels.

You have learned that to make a view interactive you need to set up a click listener for the view which says what to do when the view (button) is clicked on. The click listener can either:

  • Implement a small amount of code directly.
  • Call a method that defines the desired click behavior in the activity.

Step 3: Make the Count button 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 step, you add behavior to your layout to find and update other views.

Update the Count button so that when it is pressed, the number on the screen increases by 1.

  1. In the fragment_first.xml layout file, notice 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 it has a little more work to do, have it 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 class, add the method countMe() that takes a single View argument. This method will be invoked when the Count button is clicked and the click listener called.
private void countMe(View view) {
 
}
  1. Get the value of the showCountTextView. You will define that in the next step.
   ...
    // Get the value of the text view
    String countString = showCountTextView.getText().toString();
  1. Convert the value to a number, and increment it.
   ...
    // Convert value to a number and increment it
    Integer count = Integer.parseInt(countString);
    count++;
  1. Display the new value in the TextView by programmatically setting the text property of the TextView.
   ...
   // Display the new value in the text view.
   showCountTextView.setText(count.toString());

Here is the whole method:

private void countMe(View view) {
   // Get the value of the text view
   String countString = showCountTextView.getText().toString();
   // Convert value to a number and increment it
   Integer count = Integer.parseInt(countString);
   count++;
   // Display the new value in the text view.
   showCountTextView.setText(count.toString());
}

Step 4: Cache the TextView for repeated use

You could call findViewById() in countMe() to find showCountTextView. However, countMe() is called every time the button is clicked, and findViewById() is a relatively time consuming method to call. So it is better to find the view once and cache it.

  1. In the FirstFragment class before any methods, add a 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 be called on a View where the search for the requested ID should start, 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, false);
  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;

Here is the whole method and the declaration of showCountTextView:

TextView showCountTextView;

@Override
public View onCreateView(
       LayoutInflater inflater, ViewGroup container,
       Bundle savedInstanceState
) {
   // Inflate the layout for this fragment
   View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false);
   // Get the count text view
   showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);

   return fragmentFirstLayout;
}
  1. Run your app. Press the Count button and watch the count update.

f2b19b9209cad4f4.png

9. Task: Implement the second fragment

So 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 second screen.

c7029fe48ec2a802.png

What you’ll learn

  • How to pass information to a second fragment.

Update the layout for the second fragment

The screen for the new fragment will display a heading title and the random number. Here is what the screen will look like in the design view: a991c2db96dcafb3.png The %d indicates that part of the string will be replaced with a number. The R is just a placeholder.

Step 1: Add a TextView for the random number

  1. Open fragment_second.xml (app > res > layout > fragment_second.xml) and switch to Design View if needed. Notice that it has a ConstraintLayout that contains a TextView and a Button.
  2. Remove the chain constraints between the TextView and the Buttone49352faab20c765.png
  3. Add another TextView from the palette and drop it near the middle of the screen. This TextView will be used to display a random number between 0 and the current count from the first Fragment.
  4. Set the id to @+id/textview_random (textview_random in the Attributes panel.)
  5. Constrain the top 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 right 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, so it’s better to use a vertical bias than margins to adjust the vertical position, to help the layout look good on different screen sizes and orientations. 10. If you get a warning “Not Horizontally Constrained,” add a constraint from the start of the button to the left side of the screen and the end 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" />

Step 2: Update the TextView to display the header

  1. In fragment_second.xml, select textview_second, which currently has the text "Hello second fragment. Arg: %1$s" in the hello_second_fragment string resource.
  2. If android:text isn’t set, set it to the hello_second_fragment string resource.
android:text="@string/hello_second_fragment"
  1. Change the id to textview_header in the Attributes panel.
  2. Set the width to match_constraint, but set the height to wrap_content, so the height will change as needed to match the height of the content.
  3. Set top, left and right margins to 24dp. Left and right margins may also be referred to as “start” and “end” to support localization for right to left languages.
  4. Remove any bottom constraint.
  5. Set 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 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="@color/colorPrimaryDark"
   android:textSize="24sp"
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintStart_toStartOf="parent"
   app:layout_constraintTop_toTopOf="parent" />
ff7f9969afbd67ff.png

Step 3: Change the background color of the layout

Give your new activity a different background color than the first activity:

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

In the Attributes panel:

9948b482fb81ef5.png

Or in XML:

android:background="@color/screenBackground2"

Your app now has a completed layout for the second fragment. But if you run your app and press the Random button, it may crash. The click handler that Android Studio set up for that button needs some changes. In the next task, you will explore and fix this error.

Step 4: Examine the navigation graph

When you created your project, you chose Basic Activity as the template for the new project. When Android Studio uses the Basic Activity template for a new project, it sets up two fragments, and a navigation graph to connect the two. It also set up a button to send a string argument from the first fragment to the second. This is the button you changed into the Random button. And now you want to send a number instead of a string.

  1. Open nav_graph.xml (app > res > navigation > nav_graph.xml).

A screen similar to the Layout Editor in Design view appears. It shows the two fragments with some arrows between them. You can zoom with + and  buttons in the lower right, as you did with the Layout Editor.

  1. You can freely move the elements in the navigation editor. For example, if the fragments appear with SecondFragment to the left, drag FirstFragment to the left of SecondFragment so they appear in the order you work with them.
504c2156d46d4d6b.png

Step 5: Enable SafeArgs

This will enable SafeArgs in Android Studio.

  1. Open Gradle Scripts > build.gradle (Project: My First 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 display a message about the Gradle files being changed. Click Sync Now on the right hand side. 50cedf1769381459.png

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

  1. Choose Build > Make Project. This should rebuild everything so that Android Studio can find FirstFragmentDirections.

Troubleshooting: If the sync was not successful, confirm that you added the correct lines to the correct Gradle file. If there are still problems, check the developer’s guide about Safe Args for an updated nav_version or other changes.

Step 6: Create the argument for the navigation action

  1. In the navigation graph, click on FirstFragment, and look at the Attributes panel 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 action will happen for navigation, namely going to SecondFragment.
  3. Click on SecondFragment, and look at the Attributes panel.

The Arguments section shows Nothing 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

Step 7: Send the count to the second fragment

The Next/Random button was set up by Android Studio to go from the first fragment to the second, but it doesn’t send any information. In this step you’ll change it to send a number for the current count. You will get the current count from the text view that displays it, and pass that to the second fragment.

  1. Open FirstFragment.java (app > java > com.example.myfirstapp > FirstFragment)
  2. Find the method onViewCreated() and notice the code that sets up the click listener to go from the first fragment to the second.
  3. Replace 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 you added earlier:

public void onViewCreated(@NonNull View view, Bundle 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 button a few times. Now when you press the Random button, the second screen shows the correct string in the header, but still no count or random number, because you need to write some code to do that.

Step 8: Update SecondFragment to compute and display a random number

You have written the code to send the current count to the second fragment. The next step is to add code to SecondFragment.java to retrieve 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 current count, get the string and format it with the count, and then set it for textview_header.
Integer count = SecondFragmentArgs.fromBundle(getArguments()).getMyArg();
String countText = getString(R.string.random_heading, count);
TextView headerView = view.getRootView().findViewById(R.id.textview_header);
headerView.setText(countText);
  1. Get 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 code to convert that number into a string and set it as 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, you have built your first Android app!

Drop your comment

0Shares

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *