Appendix: Utilities
Contents:
- How to copy and rename a project
- How to delete a project
- How to extract resources
- How to add Android support libraries
- How to create images in Asset Studio
- How to compare custom objects
- How to save the state of custom objects
This appendix is a collection of tasks you might need to do as you develop the apps in the Android Developer Fundamentals practical codelabs. The tasks are not specific to one practical.
How to copy and rename a project
For some of the practical codelabs, you need to make a copy of a project before you make new changes to the project. You might also want to copy a project to use some of its code in a new project. In either case, you can copy the existing project, then rename and refactor the new project's components to use the new project's name.
In the instructions below, substitute your actual project names for ExistingProject and NewProject.
1. Copy the project
- On your computer's file system (not in Android Studio), make a copy of the ExistingProject directory.
- Rename the copied directory to NewProject.
2. Rename and refactor the project components
The old name of the project, ExistingProject, still appears throughout the packages and files in the NewProject project.
Here's how to change the file and the package references in your app to the new name:
- Start Android Studio.
- Select Open an existing Android Studio project. If you already have a project open in Android Studio, select File > Open.
- Navigate to the NewProject directory, select it, and click OK.
- Select Build > Clean Project to remove the auto-generated files.
- Click the 1:Project side-tab and choose Android from the drop-down menu to see your files in the Project: Android view.
- Expand the app > java folder.
- Right-click com.example.android.existingproject and select Refactor > Rename. A Warning dialog is displayed. Select Rename package.
- The Rename dialog is displayed. Give a new name to your project.
- Select Search in comments and strings and Search for text occurrences. Click Refactor.
- The Find: Refactoring Preview pane appears, showing the code to be refactored. Click Do Refactor.
- Expand the res > values folder and double-click the strings.xml file.
- Change the
app_name
string value to"
New Project
"
.
3. Update the build.gradle and AndroidManifest.xml files
Each app you create must have a unique application ID, as defined in the app's build.gradle
file. The steps above should have changed the build.gradle
file.
To make sure, check the file and sync the project with the Gradle file by following these steps:
- In Android Studio Project pane, expand Gradle Scripts and open build.gradle (Module: app).
- Under
defaultConfig
, check to make sure that the value of theapplicationID
key is "com.example.android.newproject". If the value isn't correct, change it manually. - Click Sync Now in the top-right corner of the Android Studio window. Tip: Another way to sync your Gradle files is to select Tools > Android > Sync Project with Gradle Files.
To make sure that the app name and package name are correct in the AndroidManifest.xml
file, follow these steps:
- Expand the app > manifests folder and double-click AndroidManifest.xml.
- Check that the
package
name is correct. It should be"com.example.android.newproject"
. If not, change it manually. - Find the statement below. If necessary, change the label to the string resource for the new app name:
android:label="@string/app_name"
How to delete a project
All the files for an Android project are contained in the project's directory on the computer's file system. To delete a project, delete its directory from your computer's file system.
Android Studio also keeps a list of recent projects that you've opened. You can remove a project from the list of recent projects, but doing so doesn't affect the actual project files. Doing this step is optional.
To remove a project from the list of recent projects in Android Studio, do one of the following:
- In the Android Studio welcome screen, place the cursor on the deleted project. Click the X that's displayed on it, or press the delete key.
- In the Android Studio welcome screen, click on the project name and select Remove From List.
- Select File > Open Recent > Manage Projects, select the project, and press the delete key or click the X that's displayed on it.
How to extract resources
Strings
For your app to be translatable into multiple languages, you must keep all your string resources in the res/values/strings.xml
file.
Creating string resources
You can manually add string resources to the strings.xml
file using the following syntax:
<string name="
string_name
">
String Value
</string>
To extract a string that you've hardcoded:
- Select the existing, hardcoded string in either XML or Java.
- Press
Alt+Enter
(Option+Enter
on a Mac), or click the orange light bulb to the right of the string. - Select Extract string resource.
- The Extract Resource window is displayed. Supply a name for Resource name: and click OK.
Accessing string resources
To reference a string resource:
- In XML, use the following syntax:
@string/
string_name
- In Java, use the following syntax:
getString(R.string.
string_name
)
Extracting dimensions
In general, keep dimensions in the dimens.xml
file instead of hardcoding them. Keeping dimensions in dimens.xml
allows you to specify different dimensions using resource qualifiers.
You extract dimensions the same way you extract strings: press Alt+Enter
(Option+Enter
on a Mac), or click the orange light bulb to the right of the dimension.
Extracting styles
If you have several elements in your app that share the same attributes, you can create a style in the style.xml
file for those attributes.
To extract existing attributes into a style, do the following:
- In the layout editor Design tab, right-click on the view in the Component Tree and select Refactor > Extract Style....
- The Extract Android Style window is displayed. Name the style and select attributes. If you want Android Studio to search the rest of the file for the selected attributes and apply the style to views where the attributes match, select Launch 'Use Style Where Possible' refactoring after the style is extracted.
- Click OK.
How to add Android support libraries
The Android Support Library provides backward-compatible versions of Android framework APIs, additional UI components, and a set of useful utilities.
For example, the RecyclerView
class is located in the Android Support package. To use RecyclerView
, you must include the RecyclerView
support library dependency in your project's build.gradle
file. The process is the same for other Android Support Library components.
To add support libraries for RecyclerView
to your Gradle file, follow these steps and refer to the screenshot below:
- In Android Studio, in your project, make sure that you are in the Project pane (1 in the screenshot) and in the Android view (2).
- In the hierarchy of files, find the Gradle Scripts folder (3).
- Expand Gradle Scripts, if necessary, and open the build.gradle (Module: app) file (4).
- Toward the end of the build.gradle (Module: app) file, find the dependencies section. There is probably a line similar to the following one:
implementation 'com.android.support:appcompat-v7:27.1.1'
- Below that line, add the following code:
implementation 'com.android.support:recyclerview-v7:27.1.1'
- Change the version number of the new line to match the latest version or version number of the existing library.
- Make sure the version numbers of all the libraries are the same and match up with the
compileSdkVersion
number. If they don't, you will get an error. - Sync your Gradle files.
- Build and run your app.
The following example shows the dependencies section of the build.gradle
file with support libraries added for RecyclerView
, if the version number were 27.1.1
.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
How to create images in Asset Studio
Use Image Asset Studio to create image assets for a launcher icon, a notification icon, or action bar icons:
- Open your app in Android Studio.
Right-click the res folder of your project and select New > Image Asset from menu.
The Asset Studio window opens. You can create a text icon, choose from available clip art, or add your own custom image.
Custom text icons
Default launcher icons called ic_launcher
and ic_launcher_round
come with your project template. To add a custom text icon:
- Open the Asset Studio, as described above.
- So that you won't overwrite the
ic_launcher
icon, change the Name of the icon toic_launcher_text
. - In the Asset Type row, select Text.
- Enter "Hello World!" into the Text field. Experiment with changing the font and the font color.
- Experiment with changing the background color in the Background Layer tab.
- Click Next. The Confirm Icon Path window shows how an icon with your specified text will be created for each resolution.
- Click Finish. The res/mipmap folder now contains the new icons.
To use the new icon:
- Open the
AndroidManifest.xml
file. Change theandroid:icon
line so that instead of referencingic_launcher_round
, it referencesic_launcher_text_round
:android:icon="@mipmap/ic_launcher_text_round"
- Run your app.
- After the app has launched, go to the home screen and open the list of apps.
- Scroll to find the new app icon listed along with the other installed apps.
Clip art icons
To add a clip art icon, follow the steps to add a custom text icon, with the following changes:
- Set the Name of the icon to
ic_launcher_clipart
. - Choose Clip Art as the Asset Type.
- In the Clip Art row, click the button that shows the current icon, the default Android.
- Select an icon from the Select Icon dialog.
Custom icons
To add a custom icon, follow the steps to add a custom text icon, with the following changes:
- Set the Name of the icon to
ic_launcher_image
. - Choose Image as the Asset Type.
- In the Path field, choose an image. The image can be one that you've added to your project, or an image on your computer.
How to compare custom objects
If your data model calls for objects to be sorted, you need to define how the objects can be compared to each other. To specify how to compare two objects and determine whether one object is bigger, smaller, or the same as the other object, use the Comparable
interface.
The Comparable
interface requires you to implement a single method: compareTo(<T> another)
, where Comparable
with, and the type of object you are comparing to.
For example, to compare your Foobar
instance to other Foobar
instances, you implement Comparable<Foobar>
. Your compareTo()
method takes Foobar
as a parameter.
The compareTo()
method should do the following:
- Return a negative integer if the object is less than the parameter.
- Return a positive integer if the object is greater than the parameter.
- Return zero if the objects are equal.
For example, to compare a list of books by publication date, you could use the following code:
@Override
public int compareTo(Book book) {
if (this.publication == book.publication) { return 0; }
else { return this.publication > book.publication ? 1 : -1;}
}
How to save the state of custom objects
In Android, you often create custom objects to represent your data model. To preserve the state of custom objects, you must be able to pass them into the savedInstanceState
bundle, and therefore your custom class must implement the Parcelable
interface. The Parcelable
implementation allows for primitive types (int
, string
, byte
, etc.) to be saved in the savedInstanceState
callback.
To save the state of custom objects, follow these steps:
- Set up the data in your custom class.
- Add the
Parcelable
implementation to your class declaration. Remember that only the primitive data types will be saved. - In Android Studio, the class declaration is underlined in red, because you need to implement the interface methods. With your cursor on the underlined text, press
Alt+Enter
(Option+Enter
on a Mac) and select Implement methods. - Select
describeContents()
andwriteToParcel(Parcel dest, int flags)
. - Click OK. The class name is still underlined, indicating that the interface is not fully implemented yet.
- Select the class name and press
Alt+Enter
(Option+Enter
on a Mac) and select Add Parcelable implementation. Android Studio adds the required code. The variables for which you want to preserve the state (primitive types) are written to theParcel
in thewriteToParcel
method.
You can now save the state of these objects using the savedInstanceState
bundles methods: putParcelable()
, putParcelableArray()
, putParcelableArrayList()
, and the respective "getter" methods.