Android to make Localizing String Resources / Translations Editor

Full source in java to use the Translations Editor to translate the string resources in our strings.xml file into a different language. We will replace all our hardcoded texts with these string resources and this way support multiple languages

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="tech.codingpoint.stringlocalizationexample.MainActivity">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        android:textSize="30sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_view"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:text="@string/do_something" />

</RelativeLayout>

MainActivity.java

package tech.codingpoint.stringlocalizationexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, R.string.toast, Toast.LENGTH_LONG).show();
            }
        });
    }
}

strings.xml

<resources>
    <string name="app_name">String Localization Example</string>
    <string name="hello_world">Hello World</string>
    <string name="do_something">Do something</string>
    <string name="toast">This is a Toast</string>
</resources>

strings.xml (de)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">String Lokalisationsbeispiel</string>
    <string name="hello_world">Hallo Welt</string>
    <string name="do_something">Tu etwas</string>
    <string name="toast">Das ist ein Toast</string>
</resources>

Leave a Comment