Change context language according to the current device language

351 views Asked by At

Alright i know it's okay to have many languages in a single app . But i couldnt find the proper way . So here is what i want to do as a start , i want the activity to detect the android device language and then change a simple text

 "@string/hello"

according to it . I know that the method is locale.getDefault().getLanguage() but i dont know how to apply it . Secondly i want to give the user the option to change the language if he wants to .

public class MainActivity extends Activity {

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


    Locale.getDefault().getLanguage();
}

Here is the simple layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
android:layout_height="match_parent"   

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.vermelha.tourword.MainActivity">

<TextView android:text="@string/hello"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"/>

</RelativeLayout>

values

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">Tour Word</string>
<string name="title_activity_main">MainActivity</string>
<string name="hello">Hello</string>
<string name="action_settings">Settings</string>

</resources>

values-tr

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tour Word</string>
<string name="title_activity_main">MainActivity</string>
<string name="hello">Merhaba!</string>
<string name="action_settings">Ayralar</string>

</resources>
1

There are 1 answers

5
Douglas Fornaro On BEST ANSWER

You have to create a new folder in res: values-es as example for Spanish, values-pt as example for Portuguese

Create a new strings.xml file

Put the same string there

values/strings.xml

<string name="app_about_title">About</string>

values-es/strings.xml

<string name="app_about_title">Acerca</string>

values-pt/strings.xml

<string name="app_about_title">Sobre</string>

Automatically when you use @string/app_about_title or via code R.string.app_about_title it will be translated If you use a language that doesn't has the translation, it will use the standard (values fodler)