### Example Preference XML for Localization
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Illustrates a basic Preference XML structure with keys assigned to `PreferenceCategory` and `Preference` items, essential for enabling Preference Localization with the Applanga plugin. Each item intended for localization must have a unique `android:key` attribute.
```xml
```
--------------------------------
### Get String with Arguments - Applanga Android
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Demonstrates how to retrieve localized strings from Applanga SDK with simple or JSON formatted arguments. This method is useful for dynamic text content.
```java
Applanga.getString('STRING_ID', 'arg1,arg2,etc', ';')
```
```java
Applanga.getString('STRING_ID', "{'arg1':'value1', 'arg2':'value2', 'arg3':'etc'}", 'json')
```
--------------------------------
### Example Menu XML with Disabled Linting in XML
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Shows a menu XML structure where one item has an ID and another has linting disabled for missing IDs using `tools:ignore="ApplangaMenuIdMissing"`. This allows for localized menu items while suppressing warnings for items that do not require localization.
```xml
```
--------------------------------
### Custom ViewPump Initialization with Applanga Interceptors
Source: https://github.com/applanga/sdk-android/blob/master/README.md
If you are using ViewPump, initialize it before `Applanga.init(...)` to ensure all interceptors remain active. If ViewPump is initialized later, cache and re-add existing interceptors, including Applanga's, to maintain functionality. This example shows how to cache, create a new ViewPump builder with Calligraphy, and re-add the cached interceptors.
```java
//cache existing (Applanga) interceptors
List interceptors = ViewPump.get().interceptors();
//create a new ViewPump.Builder
ViewPump.Builder builder = ViewPump.builder().addInterceptor(
new CalligraphyInterceptor(
new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Roboto-ThinItalic.ttf")
.setFontAttrId(R.attr.fontPath)
.build()));
//re-add cached (Applanga) interceptors
for(int i = 0; i < interceptors.size(); i++) {
builder.addInterceptor(interceptors.get(i));
}
//re-initialize ViewPump
ViewPump.init(builder.build());
```
--------------------------------
### Get Available Languages in Android with Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
Demonstrates how to retrieve a list of all available languages supported by the Applanga project. It's recommended to perform an update first to ensure the language list is synchronized. The retrieved list can then be used to populate language selection UI elements.
```java
// Perform update first to sync latest language list
Applanga.update(new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
// Get list of all project languages
List languages = Applanga.getAvailableLanguages();
// languages = ["en", "de", "fr", "es", "ja", ...]
// Build language picker UI
for (String lang : languages) {
Locale locale = new Locale(lang);
String displayName = locale.getDisplayName(locale);
// Add to language selection list
}
}
});
```
--------------------------------
### Add Applanga SDK Dependencies (Gradle)
Source: https://context7.com/applanga/sdk-android/llms.txt
Adds the Applanga SDK and Gradle plugin to your Android project. Ensure you configure repositories correctly in both project-level and app-level build files. This setup is crucial for integrating Applanga's localization features.
```gradle
// $projectDir/app/build.gradle
repositories {
maven { url 'https://maven.applanga.com/'}
}
dependencies {
implementation 'com.applanga.android:Applanga:4.0.226'
}
plugins {
id 'com.applanga.gradle' version '4.0.226'
}
```
```gradle
// $projectDir/settings.gradle
pluginManagement {
repositories {
google()
mavenCentral()
maven { url 'https://maven.applanga.com/'}
}
}
```
--------------------------------
### Setup Applanga WebView Translation Integration
Source: https://context7.com/applanga/sdk-android/llms.txt
Explains how to integrate Applanga for translating content within Android WebViews. This involves enabling JavaScript for the WebView, loading the HTML content, and then attaching the Applanga SDK to the WebView using `Applanga.attachWebView`. Additionally, a meta-data tag in `AndroidManifest.xml` is required to enable WebView translation.
```java
import android.webkit.WebView;
import com.applanga.android.Applanga;
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/index.html");
Applanga.attachWebView(webView);
```
```xml
```
--------------------------------
### Get String Array (Android Resources)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Retrieves an array of strings defined in your Android resources. The `R.array.STRING_KEY` should refer to a `` definition in your `res/values` directory.
```java
((Resources)res).getStringArray(R.array.STRING_KEY);
```
--------------------------------
### Pluralization with Arguments - Applanga Android
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Shows how to get pluralized strings based on specific rules or quantities, with support for additional arguments for dynamic content. This is essential for accurate localization across different languages.
```java
Applanga.getPluralString('STRING_ID', 'one')
```
```java
applanga.getPluralString('STRING_ID', 'one', 'arg1;arg2;etc', ';')
```
```java
Applanga.getQuantityString('STRING_ID', 42)
```
```java
applanga.getQuantityString('STRING_ID', 42, 'arg1;arg2;etc', ';')
```
--------------------------------
### HTML Text Replacement and Localization Attributes
Source: https://context7.com/applanga/sdk-android/llms.txt
This snippet demonstrates how to use Applanga's custom HTML attributes for text replacement, formatted arguments, JSON arguments, and pluralization. It initializes the Applanga script and shows examples of direct string retrieval, string retrieval with arguments, pluralization by rule and quantity, and updating translation groups via the JavaScript API.
```html
This will be replaced with translation
Welcome %{0}! You have %{1} messages.
Hello %{name}, you have %{count} items.
You have messages
```
--------------------------------
### Get Available Languages in Kotlin
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Retrieves a list of ISO language codes for all languages added to the Applanga project. This data is synced during Applanga.update(). Manual calls to Applanga.update() are recommended before using this list to ensure the most recent language data is fetched from the dashboard.
```kotlin
val languages = Applanga.getAvailableLanguages()
```
--------------------------------
### Get Pluralized String (Android Resources)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Retrieves a pluralized string based on a given quantity using Android's `getQuantityString` method. The `R.plurals.STRING_KEY` should correspond to a plural resource definition in your `res/values` directory.
```java
((Resources)res).getQuantityString(R.plurals.STRING_KEY, quantity);
```
--------------------------------
### Get Translated String with Formatted Arguments (Android Resources)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Retrieves a translated string with formatted arguments using Android's `getString` method. Placeholders like `%s` and `%d` in the string resource will be replaced by the provided arguments. Refer to `java.util.Formatter` for detailed formatting options.
```java
((Activity|Resources|Fragment)this).getString(R.string.STRING_KEY, "arg1", "arg2", "arg3");
```
--------------------------------
### Get Translated String with Formatted Arguments (Applanga Dynamic Key)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Fetches a translated string with formatted arguments using a dynamic key from Applanga. Similar to the simple dynamic key retrieval, ensure the key exists on the dashboard.
```java
Applanga.getTranslation("STRING_KEY", "arg1", "arg2", "arg3");
```
--------------------------------
### Automatic Upload of Local Strings Tag in AndroidManifest
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Configure the SDK to automatically upload a tag containing all current local strings in the app. The 'ApplangaTagLocalStringsPrefix' meta-data value acts as a prefix for the tag, which is combined with the app version. This upload occurs when the app is started or run with a debugger connected after 'Applanga.update()' is called.
```xml
...
...
```
--------------------------------
### Get Translation Array Dynamically in Java
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Retrieves a translation array using a provided string key. If the key does not exist on the dashboard, it returns null, similar to the getTranslation method. Ensure the string key exists on the Applanga dashboard to avoid null results.
```java
Applanga.getTranslationArray("STRING_KEY");
```
--------------------------------
### Get Pluralized String (Applanga Dynamic Key)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Fetches a pluralized string dynamically from Applanga based on a quantity. The string key on the Applanga dashboard should be formatted with pluralization rules (e.g., `STRING_KEY[zero]`, `STRING_KEY[one]`). This method has the same limitation as `Applanga.getTranslation`: it returns `null` if the key does not exist on the dashboard.
```java
Applanga.getQuantityTranslation("STRING_KEY", quantity);
```
--------------------------------
### Get Translated String (Applanga Dynamic Key)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Fetches a translated string using a dynamic key directly from Applanga. This method is suitable for keys not hardcoded in resource files. Note that dynamic keys are not automatically created on the Applanga dashboard; they must exist beforehand, otherwise, `null` will be returned.
```java
Applanga.getTranslation("STRING_KEY");
```
--------------------------------
### Applanga SDK Initialization (Android)
Source: https://context7.com/applanga/sdk-android/llms.txt
Demonstrates how to initialize the Applanga SDK in an Android application. Includes both automatic initialization by extending ApplangaApplication and manual initialization with a callback for custom logic.
```java
// MyApplication.java
import com.applanga.android.ApplangaApplication;
public class MyApplication extends ApplangaApplication {
// SDK automatically initializes and updates on first activity start
}
```
```xml
```
```java
// In your Activity or Application
import com.applanga.android.Applanga;
import com.applanga.android.ApplangaCallback;
Applanga.update(new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
if (success) {
// Continue loading app with updated strings
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
} else {
// Handle update failure - fallback to cached or bundled strings
Log.e("Applanga", "Failed to update translations");
}
}
});
```
--------------------------------
### Apply Applanga Gradle Plugin via Plugins DSL (Gradle)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
This demonstrates applying the Applanga Gradle Plugin using the plugins DSL in your app's build.gradle file. It also shows how to configure the pluginManagement repositories in settings.gradle to include the Applanga maven repository.
```gradle
// $projectDir/app/build.gradle
plugins {
...
id 'com.applanga.gradle' version '4.0.226'
}
// $projectDir/settings.gradle
pluginManagement {
repositories {
...
google()
mavenCentral()
maven { url 'https://maven.applanga.com/'}
}
}
```
--------------------------------
### Basic String Localization (Android)
Source: https://context7.com/applanga/sdk-android/llms.txt
Shows how to retrieve localized strings using the Applanga SDK. Covers standard Android `getString` for resource-defined strings and `Applanga.getTranslation` for dynamic keys managed in the Applanga dashboard.
```java
// Simple string localization (no code changes needed)
String welcomeText = getString(R.string.welcome_message);
textView.setText(R.string.welcome_message);
// Dynamic keys from backend (key must exist in Applanga dashboard)
String dynamicString = Applanga.getTranslation("dynamic_key_from_api");
if (dynamicString != null) {
textView.setText(dynamicString);
} else {
// Key doesn't exist, handle gracefully
textView.setText("Default text");
}
```
--------------------------------
### Get Translated String (Android Resources)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Retrieves a translated string for the current device locale using Android's built-in `getString` method with a resource ID. This assumes the string exists locally in your project's resource files.
```java
((Activity|Resources|Fragment)this).getString(R.string.STRING_KEY);
```
--------------------------------
### Pluralization Localization (Android)
Source: https://context7.com/applanga/sdk-android/llms.txt
Illustrates how to manage and retrieve pluralized strings with Applanga. This includes defining plurals in `strings.xml` and using both Android's `getQuantityString` and Applanga's `getQuantityTranslation` for dynamic plural handling.
```xml
// strings.xml plurals definition
/*
- No messages
- One message
- %d messages
*/
```
```java
int messageCount = 5;
String pluralText = getResources().getQuantityString(
R.plurals.message_count,
messageCount,
messageCount
);
// Result: "5 messages"
// Dynamic pluralization
String dynamicPlural = Applanga.getQuantityTranslation("message_count", messageCount);
```
--------------------------------
### Apply Applanga Gradle Plugin via Old Way (Gradle)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
This snippet illustrates applying the Applanga Gradle Plugin using the older `apply plugin` syntax in your app's build.gradle file. It also includes the necessary configuration for buildscript repositories and dependencies.
```gradle
// $projectDir/app/build.gradle
apply plugin: 'com.applanga.gradle'
...
buildscript {
repositories {
google()
mavenCentral()
maven { url 'https://maven.applanga.com/' }
}
dependencies {
classpath 'com.applanga.gradle:plugin:4.0.226'
}
}
```
--------------------------------
### Formatted String Arguments Localization (Android)
Source: https://context7.com/applanga/sdk-android/llms.txt
Demonstrates how to handle strings that require formatting arguments, both for standard Android resources and dynamic keys managed via Applanga. This allows for user-specific or dynamic content within translations.
```java
// Format: "Welcome %s! You have %d messages."
String greetingWithArgs = getString(R.string.greeting_format, "John", 5);
// Result: "Welcome John! You have 5 messages."
// Dynamic key with arguments
String dynamicFormatted = Applanga.getTranslation(
"dynamic_greeting",
"Sarah",
String.valueOf(10)
);
```
--------------------------------
### Display Styled String using Html.fromHtml in Java
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Shows how to display a styled string resource in an Android TextView using `Html.fromHtml()`. This method parses the HTML content and applies the styling as defined in the string resource. Ensure the `Html.FROM_HTML_MODE_LEGACY` flag is used for compatibility.
```java
textView.setText(Html.fromHtml(getString(R.string.styled_string), Html.FROM_HTML_MODE_LEGACY));
```
--------------------------------
### Manual Initialize and Update Applanga SDK (Java)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Manually initialize and update the Applanga SDK by calling Applanga.update() with a callback. This method allows control over app loading until strings are fetched, useful for displaying loading screens.
```java
//called from an activity
Applanga.update(new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean b) {
//continue loading your app
}
});
```
--------------------------------
### Map Locales to Other Locales in AndroidManifest
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Configure custom locale mappings for Applanga by specifying pairs of source and target locales. This allows treating one locale as another, for example, mapping 'es-CL' to 'es-MX'. This setting is applied across the SDK unless custom language fallback is used.
```xml
...
...
```
--------------------------------
### Enable Placeholder Conversion (Android Manifest)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Enables conversion of placeholders between iOS and Android styles within the Android Manifest. Common placeholders are supported across both platforms and are not converted by default. Specific iOS placeholders like `%@` are converted to `%s`.
```xml
...
...
```
--------------------------------
### Display Styled Strings with HTML in Android
Source: https://context7.com/applanga/sdk-android/llms.txt
Demonstrates how to display strings with basic HTML formatting in an Android TextView. It involves escaping HTML tags in `strings.xml` and then using `Html.fromHtml` to render the styled text. This method is useful for simple text formatting like bold or italics.
```java
// strings.xml (escape HTML tags)
/*
Hello, <b>I am bold</b> and <i>italic</i>.
*/
// Display styled text
TextView styledTextView = findViewById(R.id.styled_text);
styledTextView.setText(
Html.fromHtml(
getString(R.string.styled_text),
Html.FROM_HTML_MODE_LEGACY
)
);
// Result: "Hello, I am bold and italic." (with formatting)
```
--------------------------------
### Auto Initialize Applanga SDK (Java)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Initialize the Applanga SDK by extending your Application class from ApplangaApplication. This is the simplest method for integrating Applanga. Ensure to include the necessary import statement.
```java
import com.applanga.android.ApplangaApplication;
public class MyApplication extends ApplangaApplication {
...
}
```
--------------------------------
### Android Draft Mode Activation using Touch Events
Source: https://context7.com/applanga/sdk-android/llms.txt
This Java snippet shows how to enable Applanga's Draft Mode in an Android application by intercepting touch events. Draft Mode requires a specific gesture (6 fingers for 6 seconds) and entry of the app secret. The `dispatchTouchEvent` method must be overridden to pass touch events to Applanga.
```java
import android.view.MotionEvent;
import com.applanga.android.Applanga;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// Enable Draft Mode: hold 6 fingers for 6 seconds
// Enter first 4 characters of app secret when prompted
Applanga.dispatchTouchEvent(ev, this);
return super.dispatchTouchEvent(ev);
}
```
--------------------------------
### Enable Show ID Mode for String Identification
Source: https://github.com/applanga/sdk-android/blob/master/README.md
The `showIdMode` feature displays all string IDs instead of their translations, which is useful for identifying untagged strings on the screen, especially those set at runtime. Enable this mode before initializing your screen for reliable string ID collection. Note that enabling this mode after a screen has been shown requires recreating the activity.
```java
Applanga.setShowIdModeEnabled(true);
```
--------------------------------
### Add Applanga Meta to Gitignore
Source: https://github.com/applanga/sdk-android/blob/master/README.md
This shows how to add the `applanga_meta.xml` file to your `.gitignore` file to prevent it from being committed to your repository. This file is automatically generated by the Applanga plugin.
```gitignore
...
*applanga_meta.xml
```
--------------------------------
### Initialize Applanga in WebView - JavaScript
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Initializes the Applanga SDK within a WebView using JavaScript. This function recursively calls itself until ApplangaNative is available, then loads the script. This is necessary for Applanga to translate web content.
```javascript
window.initApplanga = function() {
if(typeof window.ApplangaNative !== 'undefined'){ window.ApplangaNative.loadScript();
} else { setTimeout(window.initApplanga, 180); }
};
window.initApplanga();
```
--------------------------------
### Android Programmatic Screenshot Capture with Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
This Java snippet demonstrates how to programmatically capture screenshots within an Android app using the Applanga SDK. It allows associating screenshots with specific tags, including additional UI element IDs, and optionally using OCR for untagged text. It also shows how to programmatically display the screenshot menu if Draft Mode is enabled.
```java
// Capture screenshot and assign to tag
String tagName = "main_screen";
List additionalIds = new ArrayList<>();
additionalIds.add("header_title");
additionalIds.add("submit_button");
additionalIds.add("error_message");
Applanga.captureScreenshot(tagName, additionalIds);
// With OCR for untagged text (slower processing)
Applanga.captureScreenshot(tagName, additionalIds, true);
// Show screenshot menu programmatically (requires Draft Mode)
Applanga.setScreenShotMenuVisible(true);
```
--------------------------------
### Capture Compose Screenshot with IDs in Android
Source: https://context7.com/applanga/sdk-android/llms.txt
This Kotlin code snippet demonstrates how to capture screenshots of Jetpack Compose UI with Applanga's Show ID Mode enabled and disabled. It utilizes the createAndroidComposeRule for testing Compose UI, fetches semantics nodes, extracts string positions, and converts them to JSON format for Applanga's screenshot capturing functionality. Ensure Applanga SDK and Compose testing dependencies are correctly set up.
```kotlin
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.semantics.SemanticsNode
import com.applanga.android.Applanga
import org.junit.Rule
import org.junit.Test
class ComposeScreenshotTest {
@get:Rule
val composeTestRule = createAndroidComposeRule(MainActivity::class.java)
private fun getStringPositions(
nodes: Iterable,
positions: Map = mapOf()
): Map {
var mutablePositions = positions.toMutableMap()
nodes.forEach { node ->
val pos = Rect(node.positionInWindow, node.size.toSize())
node.config.forEach { configValue ->
if (configValue.key.name == "Text") {
val values = configValue.value
if (values is Collection<*>) {
values.forEach {
if (it is AnnotatedString) {
mutablePositions[it.text] = pos
}
}
}
}
}
mutablePositions = getStringPositions(
node.children,
positions = mutablePositions
).toMutableMap()
}
return mutablePositions
}
private fun stringPositionsToJson(
positions: Map,
isInShowIdMode: Boolean
): String {
var json = "{\"ALStringPositions\":["
positions.forEach {
json += "{"
if (isInShowIdMode) {
json += "\"key\": \"${it.key}\","
}
json += "\"value\": \"${it.key}\",
```
--------------------------------
### Handle Styled Strings with HTML Escaping in XML
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Demonstrates how to escape HTML tags within string resources in `strings.xml` to ensure correct rendering of styled strings. If not escaped, HTML tags will be stripped during upload. Translating directly on the Applanga dashboard bypasses the need for escaping.
```xml
Hello, <b>I am bold</b>.
```
--------------------------------
### Applanga Localization Finish Callback
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Shows how to receive notifications when Applanga finishes its localization process. This is useful for displaying loading screens or performing actions after translations are ready. Override the `onLocalizeFinished` method in your Application class that extends `ApplangaApplication`.
```java
public class MyApplication extends ApplangaApplication {
...
@Override
public void onLocalizeFinished(boolean success) {
//do something on finished localization
}
...
}
```
--------------------------------
### Auto Initialize Applanga SDK (XML)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Configure your AndroidManifest.xml to use ApplangaApplication as the application's name if you do not have a custom Application class. This allows for automatic initialization without code changes.
```xml
...
```
--------------------------------
### Proguard Rules for Applanga Android SDK
Source: https://context7.com/applanga/sdk-android/llms.txt
Apply these Proguard rules to your `proguard-rules.pro` file to ensure that Applanga SDK functions correctly, particularly concerning the preservation of R classes and methods annotated with `JavascriptInterface` for web view interactions.
```proguard
# proguard-rules.pro
-keep class **.R$* {
;
}
-keepattributes JavascriptInterface
-keepclassmembers class * {
@android.webkit.JavascriptInterface ;
}
```
--------------------------------
### Android UI Test Screenshot Capture with Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
This Java code demonstrates how to capture screenshots during Android UI tests using Applanga. It involves enabling 'Show ID Mode' for accurate string tagging before capturing, then disabling it for a normal screenshot. The test uses `ActivityScenarioRule` and `Thread.sleep` to manage UI state and rendering.
```java
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import com.applanga.android.Applanga;
import org.junit.Rule;
import org.junit.Test;
public class ScreenshotTest {
@Rule
public ActivityScenarioRule activityRule =
new ActivityScenarioRule<>(MainActivity.class);
@Test
public void captureMainScreenshot() {
// Enable Show ID Mode for accurate string tagging
Applanga.setShowIdModeEnabled(true);
activityRule.getScenario().onActivity(activity -> {
activity.recreate();
});
// Wait for UI to render
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Capture with IDs visible
List ids = new ArrayList<>();
Applanga.captureScreenshot("login_screen_ids", ids);
// Disable Show ID Mode
Applanga.setShowIdModeEnabled(false);
activityRule.getScenario().onActivity(activity -> {
activity.recreate();
});
// Wait for UI refresh
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Capture normal screenshot
Applanga.captureScreenshot("login_screen", ids);
}
}
```
--------------------------------
### Capture Screenshots with OCR Enabled
Source: https://github.com/applanga/sdk-android/blob/master/README.md
This method captures screenshots programmatically and enables Optical Character Recognition (OCR) to identify untagged text. Use this when the SDK cannot automatically find the correct tags for text strings. Be aware that enabling OCR may slow down screenshot processing.
```java
Applanga.captureScreenshot(tag, applangaIDs, true);
```
--------------------------------
### Legacy Language Switching in Android with Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
Provides methods for legacy language switching in Android applications using Applanga. `Applanga.setLanguage` changes the language and returns a boolean indicating success, requiring manual UI recreation. `Applanga.setLanguageAndUpdate` combines setting the language with updating translations, followed by UI recreation.
```java
// Legacy method (stores to device settings)
boolean success = Applanga.setLanguage("de");
if (success) {
// Language set successfully, recreate activity
recreate();
}
// Combined set and update
Applanga.setLanguageAndUpdate("fr", new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
recreate();
}
});
// Reset to device language
Applanga.setLanguage(null);
```
--------------------------------
### Enable Custom Language Fallback in AndroidManifest
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Define a custom fallback language order for specific languages using an XML resource file. This meta-data value points to an XML file that specifies a prioritized list of languages to use when a string is not found for a given language, overriding system or default fallbacks for those languages.
```xml
...
...
```
```xml
- es-MX
- es-US
- es
- de-AT
- en
```
--------------------------------
### Trigger Full Applanga Update with Callback in Java
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Initiates a full Applanga content update, fetching the base language and localized versions for the device's current language. The `onLocalizeFinished` callback is invoked upon completion, indicating success or failure. This method updates only the main group.
```java
Applanga.update(new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
//called if update is complete
}
});
```
--------------------------------
### Attach WebView for Translation - Java
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Integrates Applanga translation capabilities into Android WebViews. JavaScript must be enabled for the WebView. The WebView is passed to Applanga.attachWebView(). A corresponding meta-data tag must be added to the AndroidManifest.xml. Initialization within the WebView is handled via JavaScript.
```java
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("html_file_path");
Applanga.attachWebView(myWebView);
```
--------------------------------
### Enable Automatic Applanga Settings File Update (Gradle)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Configuration in `build.gradle` to automatically update the Applanga Settings File. This is useful for ensuring translation updates are available even without an internet connection. The task triggers generation if changes are detected. A warning is printed if run offline.
```gradle
// for all builds:
applanga.settingsFileAutoUpdate = true
// only for release builds:
applanga.settingsFileAutoUpdateRelease = true
```
--------------------------------
### Disable Applanga Preference Key Lint Warning in XML
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Demonstrates how to disable Applanga's lint warnings for missing preference keys by adding `tools:ignore="ApplangaPreferenceKeyMissing"` to a preference item or its parent in the XML layout. This is useful when localization is not required for specific items.
```xml
```
--------------------------------
### Applanga Build Configuration in Gradle
Source: https://context7.com/applanga/sdk-android/llms.txt
Configure Applanga's auto-update settings for your build process using the `applanga` block in your app's `build.gradle` file. You can enable auto-updating on all builds or only on release builds.
```gradle
// app/build.gradle
applanga {
// Auto-update settings file on all builds
settingsFileAutoUpdate = true
// Only auto-update on release builds
settingsFileAutoUpdateRelease = true
}
```
--------------------------------
### Android 13+ Per-App Language Switching with Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
Implements language switching for Android 13 and above using `AppCompatDelegate.setApplicationLocales`. This method allows setting language preferences per application. After changing the locale, it updates Applanga strings for the new language. Dependencies include `androidx.appcompat` and `androidx.core.os`.
```java
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.os.LocaleListCompat;
// Recommended: Use per-app language preferences (Android 13+)
public void changeLanguage(String languageCode) {
// Set language using AppCompat
LocaleListCompat appLocale = LocaleListCompat.forLanguageTags(languageCode);
AppCompatDelegate.setApplicationLocales(appLocale);
// Update Applanga strings for new language
List languages = new ArrayList<>();
languages.add(languageCode);
Applanga.update(null, languages, new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
// Language changed and strings updated
}
});
}
// Usage
changeLanguage("de"); // German
changeLanguage("fr-CA"); // Canadian French
changeLanguage("es-MX"); // Mexican Spanish
```
--------------------------------
### Retrieve Named Arguments String (Deprecated)
Source: https://github.com/applanga/sdk-android/blob/master/README.md
DEPRECATED: This method retrieves a translated string using named arguments. Placeholders like `%{someArg}` in the string are replaced by values from a provided `Map`. This functionality will be removed in a future release. Consider using formatted arguments instead.
```java
Map args = new Map();
args.put("someArg","awesome");
args.put("anotherArg","crazy");
Applanga.getString("STRING_KEY", args);
```
--------------------------------
### String Array Localization (Android)
Source: https://context7.com/applanga/sdk-android/llms.txt
Covers the localization of string arrays using Applanga. This includes retrieving standard string arrays from `strings.xml` and fetching dynamic string arrays directly from the Applanga dashboard using `Applanga.getTranslationArray`.
```xml
// strings.xml
/*
- Monday
- Tuesday
- Wednesday
*/
```
```java
String[] days = getResources().getStringArray(R.array.days_of_week);
// Dashboard IDs: days_of_week[0], days_of_week[1], days_of_week[2]
// Dynamic string array
String[] dynamicArray = Applanga.getTranslationArray("custom_array");
if (dynamicArray != null) {
adapter.setData(dynamicArray);
}
```
--------------------------------
### Configure .gitignore for Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
Excludes Applanga's metadata file from version control. This ensures that generated or temporary Applanga files are not committed to your repository.
```plaintext
*applanga_meta.xml
```
--------------------------------
### Android Manifest Permission for Draft Mode
Source: https://context7.com/applanga/sdk-android/llms.txt
This XML snippet declares the necessary permission in the AndroidManifest.xml file required for Applanga's Draft Mode menu to function. This permission allows the app to display system alert windows.
```xml
```
--------------------------------
### Basic Jetpack Compose Integration for Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
Integrate Applanga into your Jetpack Compose UI by utilizing `stringResource` and `stringArrayResource` composables. Applanga automatically handles the resolution of these string resources, allowing for seamless localization within your Compose functions.
```kotlin
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.stringArrayResource
@Composable
fun WelcomeScreen() {
// Applanga automatically handles stringResource()
Text(text = stringResource(R.string.welcome_title))
// String arrays also supported
val menuItems = stringArrayResource(R.array.menu_options)
menuItems.forEach {
Text(text = item)
}
}
```
--------------------------------
### Ignore Non-Translatable Strings in XML
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Demonstrates how to mark strings as non-translatable in XML. Strings with `translatable="false"` or within files named `donottranslate.xml` (or prefixed with `donottranslate-`) are ignored by Applanga during upload.
```xml
This string won't be uploaded
```
--------------------------------
### Enable System Language Fallback in AndroidManifest
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Override the default Applanga language fallback order with the device's system language priority. This meta-data value determines the order in which translated strings are downloaded or fallbacks are attempted when a string is not found for the current language.
```xml
...
...
```
--------------------------------
### Translate HTML Content with Arguments - HTML
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Allows passing arguments to Applanga for string formatting within HTML content. Arguments are parsed as a comma-separated list by default, replacing placeholders like %{arrayIndex}. A custom separator can be defined using 'applanga-args-separator'. Direct calls use Applanga.getString('STRING_ID', 'arg1,arg2,etc').
```html
***This will be replaced with the value of STRING_ID***
***and formatted with arguments***
***This will be replaced with the value of STRING_ID***
```
--------------------------------
### Capture Screenshots Programmatically in Android
Source: https://github.com/applanga/sdk-android/blob/master/README.md
This function allows you to programmatically capture screenshots within your Android application. You can provide a tag and a list of Applanga IDs to associate with the screenshot. The SDK attempts to find all IDs on the screen automatically, but you can also specify additional IDs.
```java
String tag = "Mainmenu";
List applangaIDs = new ArrayList<>();
applangaIDs.add("StringID1");
applangaIDs.add("StringID2");
Applanga.captureScreenshot(tag, applangaIDs);
```
--------------------------------
### Enable Draft Mode - Applanga Android
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Provides the Java code to override `dispatchTouchEvent` for enabling Applanga's Draft Mode. Draft Mode allows for on-device testing of translations and is activated by a multi-finger gesture.
```java
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Applanga.dispatchTouchEvent(ev, this);
return super.dispatchTouchEvent(ev);
}
```
--------------------------------
### Update Applanga Translations and Manage Languages
Source: https://context7.com/applanga/sdk-android/llms.txt
Shows how to update all translations for the default language and main group, or specific groups and languages. It uses the `Applanga.update` method with a callback to handle the completion of the localization process, often used to refresh the UI.
```java
// Update default language and main group
Applanga.update(new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
// Refresh UI after update
recreate();
}
});
// Update specific groups and languages
List groups = new ArrayList<>();
groups.add("onboarding");
groups.add("checkout_flow");
groups.add("settings");
List languages = new ArrayList<>();
languages.add("en");
languages.add("de");
languages.add("fr");
languages.add("es-MX");
Applanga.update(groups, languages, new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
if (success) {
Log.d("Applanga", "Successfully updated groups and languages");
}
}
});
```
--------------------------------
### Set App Language (Legacy) - Java
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Allows changing the app's language at runtime using legacy Applanga methods. It's recommended to follow with an Applanga.update() call or use setLanguageAndUpdate. The language parameter should be an ISO language code. The method returns true if the language is set or already current. Recreating the activity is necessary for changes to take effect. To reset to device language, call setLanguage(null) and restart the app.
```java
boolean success = Applanga.setLanguage(language);
// or
Applanga.setLanguageAndUpdate(language, applangaCallback);
// To reset to device language:
Applanga.setLanguage(null);
```
--------------------------------
### Android Manifest Configuration for Applanga
Source: https://context7.com/applanga/sdk-android/llms.txt
Configure Applanga SDK behavior by adding meta-data tags within the `` tag in your AndroidManifest.xml. These tags control aspects like default update groups and languages, draft mode, placeholder conversion, language mapping, and fallback mechanisms.
```xml
```
--------------------------------
### Trigger Specific Applanga Update with Groups and Languages in Java
Source: https://github.com/applanga/sdk-android/blob/master/README.md
Triggers an Applanga content update for specified groups and languages. This method allows for granular control over which content is fetched. The `onLocalizeFinished` callback signals the completion of the update process.
```java
List groups = new ArrayList<>();
groups.add("GroupA");
groups.add("GroupB");
List languages = new ArrayList<>();
languages.add("en");
languages.add("de");
languages.add("fr");
Applanga.update(groups, languages, new ApplangaCallback() {
@Override
public void onLocalizeFinished(boolean success) {
//called if update is complete
}
});
```