Supporting Different Languages
PREVIOUS NEXT
THIS CLASS TEACHES YOU TO
- Create Locale Directories and String Files
- Use the String Resources
YOU SHOULD ALSO READ
- Localization Checklist
- Localization with Resources
It’s always a good practice to extract UI strings from your app code and keep them in an external file. Android makes this easy with a resources directory in each Android project.
If you created your project using the Android SDK Tools (readCreating an Android Project), the tools create a
res/
directory in the top level of the project. Within this res/
directory are subdirectories for various resource types. There are also a few default files such as res/values/strings.xml
, which holds your string values.Create Locale Directories and String Files
To add support for more languages, create additional
values
directories inside res/
that include a hyphen and the ISO language code at the end of the directory name. For example, values-es/
is the directory containing simple resourcess for the Locales with the language code "es". Android loads the appropriate resources according to the locale settings of the device at run time. For more information, see Providing Alternative Resources.
Once you’ve decided on the languages you will support, create the resource subdirectories and string resource files. For example:
MyProject/ res/ values/ strings.xml values-es/ strings.xml values-fr/ strings.xml
Add the string values for each locale into the appropriate file.
At runtime, the Android system uses the appropriate set of string resources based on the locale currently set for the user's device.
For example, the following are some different string resource files for different languages.
English (default locale),
/values/strings.xml
:<?xml version="1.0" encoding="utf-8"?> <resources> <string name="title">My Application</string> <string name="hello_world">Hello World!</string> </resources>
Spanish,
/values-es/strings.xml
:<?xml version="1.0" encoding="utf-8"?> <resources> <string name="title">Mi Aplicación</string> <string name="hello_world">Hola Mundo!</string> </resources>
French,
/values-fr/strings.xml
:<?xml version="1.0" encoding="utf-8"?> <resources> <string name="title">Mon Application</string> <string name="hello_world">Bonjour le monde !</string> </resources>
Note: You can use the locale qualifier (or any configuration qualifer) on any resource type, such as if you want to provide localized versions of your bitmap drawable. For more information, see Localization.
Use the String Resources
You can reference your string resources in your source code and other XML files using the resource name defined by the
<string>
element's name
attribute.
In your source code, you can refer to a string resource with the syntax
R.string.<string_name>
. There are a variety of methods that accept a string resource this way.
For example:
// Get a string resource from your app'sResources
String hello =getResources()
.getString(R.string.hello_world); // Or supply a string resource to a method that requires a string TextView textView = new TextView(this); textView.setText(R.string.hello_world);
In other XML files, you can refer to a string resource with the syntax
@string/<string_name>
whenever the XML attribute accepts a string value.
For example:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" />
Supporting Different Screens
PREVIOUS NEXT
THIS LESSON TEACHES YOU TO
- Create Different Layouts
- Create Different Bitmaps
YOU SHOULD ALSO READ
- Designing for Multiple Screens
- Providing Resources
- Iconography design guide
Android categorizes device screens using two general properties: size and density. You should expect that your app will be installed on devices with screens that range in both size and density. As such, you should include some alternative resources that optimize your app’s appearance for different screen sizes and densities.
- There are four generalized sizes: small, normal, large, xlarge
- And four generalized densities: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi)
To declare different layouts and bitmaps you'd like to use for different screens, you must place these alternative resources in separate directories, similar to how you do for different language strings.
Also be aware that the screens orientation (landscape or portrait) is considered a variation of screen size, so many apps should revise the layout to optimize the user experience in each orientation.
Create Different Layouts
To optimize your user experience on different screen sizes, you should create a unique layout XML file for each screen size you want to support. Each layout should be saved into the appropriate resources directory, named with a -<screen_size>
suffix. For example, a unique layout for large screens should be saved under res/layout-large/
.
Note: Android automatically scales your layout in order to properly fit the screen. Thus, your layouts for different screen sizes don't need to worry about the absolute size of UI elements but instead focus on the layout structure that affects the user experience (such as the size or position of important views relative to sibling views).
For example, this project includes a default layout and an alternative layout for large screens:
MyProject/
res/
layout/
main.xml
layout-large/
main.xml
The file names must be exactly the same, but their contents are different in order to provide an optimized UI for the corresponding screen size.
Simply reference the layout file in your app as usual:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
The system loads the layout file from the appropriate layout directory based on screen size of the device on which your app is running. More information about how Android selects the appropriate resource is available in the Providing Resources guide.
As another example, here's a project with an alternative layout for landscape orientation:
MyProject/
res/
layout/
main.xml
layout-land/
main.xml
By default, the layout/main.xml
file is used for portrait orientation.
If you want to provide a special layout for landscape, including while on large screens, then you need to use both the large
and land
qualifier:
MyProject/
res/
layout/ # default (portrait)
main.xml
layout-land/ # landscape
main.xml
layout-large/ # large (portrait)
main.xml
layout-large-land/ # large landscape
main.xml
Note: Android 3.2 and above supports an advanced method of defining screen sizes that allows you to specify resources for screen sizes based on the minimum width and height in terms of density-independent pixels. This lesson does not cover this new technique. For more information, read Designing for Multiple Screens.
Create Different Bitmaps
You should always provide bitmap resources that are properly scaled to each of the generalized density buckets: low, medium, high and extra-high density. This helps you achieve good graphical quality and performance on all screen densities.
To generate these images, you should start with your raw resource in vector format and generate the images for each density using the following size scale:
- xhdpi: 2.0
- hdpi: 1.5
- mdpi: 1.0 (baseline)
- ldpi: 0.75
This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
Note: Low-density (ldpi) resources aren’t always necessary. When you provide hdpi assets, the system scales them down by one half to properly fit ldpi screens.
For more tips and guidelines about creating icon assets for your app, see the
Supporting Different Platform Versions
PREVIOUS NEXT
THIS LESSON TEACHES YOU TO
- Specify Minimum and Target API Levels
- Check System Version at Runtime
- Use Platform Styles and Themes
YOU SHOULD ALSO READ
- Android API Levels
- Android Support Library
While the latest versions of Android often provide great APIs for your app, you should continue to support older versions of Android until more devices get updated. This lesson shows you how to take advantage of the latest APIs while continuing to support older versions as well.
The dashboard for Platform Versions is updated regularly to show the distribution of active devices running each version of Android, based on the number of devices that visit the Google Play Store. Generally, it’s a good practice to support about 90% of the active devices, while targeting your app to the latest version.
Tip: In order to provide the best features and functionality across several Android versions, you should use the Android Support Library in your app, which allows you to use several recent platform APIs on older versions.
Specify Minimum and Target API Levels
The AndroidManifest.xml file describes details about your app and identifies which versions of Android it supports. Specifically, the minSdkVersion
and targetSdkVersion
attributes for the <uses-sdk
element identify the lowest API level with which your app is compatible and the highest API level against which you’ve designed and tested your app.
For example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
...</manifest>
As new versions of Android are released, some style and behaviors may change. To allow your app to take advantage of these changes and ensure that your app fits the style of each user's device, you should set thetargetSdkVersion
value to match the latest Android version available.
Check System Version at Runtime
Android provides a unique code for each platform version in the Build
constants class. Use these codes within your app to build conditions that ensure the code that depends on higher API levels is executed only when those APIs are available on the system.
private void setUpActionBar() {
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
Note: When parsing XML resources, Android ignores XML attributes that aren’t supported by the current device. So you can safely use XML attributes that are only supported by newer versions without worrying about older versions breaking when they encounter that code. For example, if you set the targetSdkVersion="11"
, your app includes the ActionBar
by default on Android 3.0 and higher. To then add menu items to the action bar, you need to set android:showAsAction="ifRoom"
in your menu resource XML. It's safe to do this in a cross-version XML file, because the older versions of Android simply ignore the showAsAction
attribute (that is, you do not need a separate version in res/menu-v11/
).
Use Platform Styles and Themes
Android provides user experience themes that give apps the look and feel of the underlying operating system. These themes can be applied to your app within the manifest file. By using these built in styles and themes, your app will naturally follow the latest look and feel of Android with each new release.
To make your activity look like a dialog box:
<activity android:theme="@android:style/Theme.Dialog">
To make your activity have a transparent background:
<activity android:theme="@android:style/Theme.Translucent">
To apply your own custom theme defined in /res/values/styles.xml
:
<activity android:theme="@style/CustomTheme">
To apply a theme to your entire app (all activities), add the android:theme
attribute to the <application>
element:
<application android:theme="@style/CustomTheme">
Managing the Activity Lifecycle
GET STARTED
DEPENDENCIES AND PREREQUISITES
- How to create an Android project (seeCreating an Android Project)
YOU SHOULD ALSO READ
- Activities
TRY IT OUT
Download the demo
ActivityLifecycle.zip
As a user navigates through, out of, and back to your app, theActivity
instances in your app transition between different states in their lifecycle. For instance, when your activity starts for the first time, it comes to the foreground of the system and receives user focus. During this process, the Android system calls a series of lifecycle methods on the activity in which you set up the user interface and other components. If the user performs an action that starts another activity or switches to another app, the system calls another set of lifecycle methods on your activity as it moves into the background (where the activity is no longer visible, but the instance and its state remains intact).
Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot.
This class explains important lifecycle callback methods that each Activity
instance receives and how you can use them so your activity does what the user expects and does not consume system resources when your activity doesn't need them.
Lessons
- Starting an Activity
- Learn the basics about the activity lifecycle, how the user can launch your app, and how to perform basic activity creation.
- Pausing and Resuming an Activity
- Learn what happens when your activity is paused (partially obscured) and resumed and what you should do during these state changes.
- Stopping and Restarting an Activity
- Learn what happens when the user completely leaves your activity and returns to it.
- Recreating an Activity
- Learn what happens when your activity is destroyed and how you can rebuild the activity state when necessary.
No comments:
Post a Comment