Page Summary
-
ML Kit can translate text between more than 50 languages using on-demand dynamic model downloads.
-
You need to create a
Translatorobject, download the necessary language model, and then use thetranslate()method to translate text. -
Explicit model management allows you to pre-download, delete, and control language models on the device for optimized performance.
-
It's recommended to download models over Wi-Fi and delete unused models to save storage space and bandwidth.
-
Ensure the
close()method is called when theTranslatorobject is no longer needed, potentially using LifecycleObserver for easier management in Fragments or Activities.
You can use ML Kit to translate text between languages. ML Kit can translation between more than 50 languages.
Try it out
- Play around with the sample app to see an example usage of this API.
Before you begin
- In your project-level
build.gradlefile, make sure to include Google's Maven repository in both yourbuildscriptandallprojectssections. - Add the dependencies for the ML Kit Android libraries to your module's
app-level gradle file, which is usually
app/build.gradle:dependencies { // ... implementation 'com.google.mlkit:translate:17.0.3' }
Translate a string of text
To translate a string between two languages:
Create a
Translatorobject, configuring it with the source and target languages:Kotlin
// Create an English-German translator: val options = TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.ENGLISH) .setTargetLanguage(TranslateLanguage.GERMAN) .build() val englishGermanTranslator = Translation.getClient(options)
Java
// Create an English-German translator: TranslatorOptions options = new TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.ENGLISH) .setTargetLanguage(TranslateLanguage.GERMAN) .build(); final Translator englishGermanTranslator = Translation.getClient(options);
If you don't know the language of the input text, you can use the Language Identification API which gives you a language tag. Then convert the tag to a
TranslateLanguageusingTranslateLanguage.fromLanguageTag().Avoid keeping too many language models on the device at once.
Make sure the required translation model has been downloaded to the device. Don't call
translate()until you know the model is available.Kotlin
var conditions = DownloadConditions.Builder()