Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Sunday, January 3, 2016

Change languages in app via strings.xml

Change languages in app via strings.xml


I'm new in java and actually developing a game app and I wanted add a feature which could change languages in the game. I already tried several tutorial methods, but it didn't work out, or rather my app crashes. Also tried some answers here in stackoverflow, also didn't work .

I already made 2 strings.xml. One is the default (english), the other one is the translated version (fil)

Here's my code

import android.app.Activity;  import android.os.Bundle;  import android.view.View;  import android.widget.Button;  import android.widget.Toast;    public class LanguageActivity extends Activity {    private static Button button_fil;    private static Button button_eng;      public void onButtonClickListener() {      button_fil = (Button) findViewById(R.id.btnFilipino);      button_fil.setOnClickListener(        new View.OnClickListener() {@          Override          public void onClick(View v) {            Toast.makeText(LanguageActivity.this, "Filipino Language", Toast.LENGTH_SHORT).show();          }        }      );        button_eng = (Button) findViewById(R.id.btnEnglish);      button_eng.setOnClickListener(        new View.OnClickListener() {@          Override          public void onClick(View v) {            Toast.makeText(LanguageActivity.this, "English Language", Toast.LENGTH_SHORT).show();          }        }      );      }        public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.language);      onButtonClickListener();      }  }

Here's the string. The string(tl) one has the dir of values-tl string.xml

< resources >    < string name = "app_name" > Ling - O - Ragon < /string>        Istart    < string name = "btnTrivias" > Trivia < /string>      Setings    < string name = "btnExit" > Exit < /string>      balik    < string name = "txtSettings" > Setings < /string>      Mga Linguahe    < string name = "btnAbout" > Tungkol sa mga gumawa < /string>      Mga Suhesyon    < string name = "btnFilipino" > Filipino < /string>      English    < string name = "txtTell" > Tell us what concerns you. < /string>      This might help us improve this app :)    < string name = "btnSend" > I - send < /string>      Greetings    < string name = "btnTravel" > Travel < /string>      Date and Time    < string name = "txtTranslate" > Isalin < /string>      next        //Oneone    < string name = "btnMaganda" > Maganda < /string>      Mabuti    < string name = "btnMarami" > Marami < /string>              Kumusta ka    < string name = "langselection" > Pumili ng Linguahe < /string>      Choose the language    < string - array name = "languages" >    < item > Select language < /item>          Filipino?    < item > English < /item>              < /resources>

Thanks a lot!

Answer by Zumry Mohamed for Change languages in app via strings.xml


Always follow official tutorial

Add your string files here.

if you don't have one, Create values-fil folder in the MyProject/res folder.

enter image description here

Check this if you want to handle Phone system language changes.

Answer by Rubin Nellikunnathu for Change languages in app via strings.xml


Try this example please. Maybe it will help you. Here i used a spinner for selecting language.

In your actvity

import java.util.Locale;  import android.os.Bundle;  import android.app.Activity;  import android.content.Intent;  import android.content.res.Configuration;  import android.content.res.Resources;  import android.util.DisplayMetrics;  import android.view.View;  import android.widget.AdapterView;  import android.widget.Button;  import android.widget.Spinner;  import android.widget.Toast;  import android.widget.AdapterView.OnItemSelectedListener;    public class AndroidLocalize extends Activity {      Spinner spinnerctrl;      Button btn;      Locale myLocale;        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);          spinnerctrl = (Spinner) findViewById(R.id.spinner1);          spinnerctrl.setOnItemSelectedListener(new OnItemSelectedListener() {                public void onItemSelected(AdapterView parent, View view,                      int pos, long id) {                    if (pos == 1) {                        Toast.makeText(parent.getContext(),                              "You have selected Tamil", Toast.LENGTH_SHORT)                              .show();                      setLocale("ta");                  } else if (pos == 2) {                        Toast.makeText(parent.getContext(),                              "You have selected Hindi", Toast.LENGTH_SHORT)                              .show();                      setLocale("hi");                  } else if (pos == 3) {                        Toast.makeText(parent.getContext(),                              "You have selected English", Toast.LENGTH_SHORT)                              .show();                      setLocale("en");                  }                }                public void onNothingSelected(AdapterView arg0) {                  // TODO Auto-generated method stub              }            });      }        public void setLocale(String lang) {            myLocale = new Locale(lang);          Resources res = getResources();          DisplayMetrics dm = res.getDisplayMetrics();          Configuration conf = res.getConfiguration();          conf.locale = myLocale;          res.updateConfiguration(conf, dm);          Intent refresh = new Intent(this, AndroidLocalize.class);          startActivity(refresh);      }  }  

in your XML

                               

and create folders in your res like

then add strings.xml for your language like

        Androidlocalization      Hello world!      AndroidLocalize      ???? ???? !!      ??? ???? ??? ?? ???? ?? ??????? ???? ????? ??? ?? ??? ????!!!!      Choose the language                  Select language          ?????          ?????          English            

please update your manifest also , i hope that will resolve your problem..

update like this.

                                                                                                                           

Answer by Kris for Change languages in app via strings.xml


When you are supporting multiple languages , You need to create separate values folder like values-fr for instance and put your stings.xml file inside this folder . Should work. Hope this helps!

Answer by Vinayagam.D for Change languages in app via strings.xml


        Androidlocalization      Hello world!      AndroidLocalize      ???? ???? !!      ??? ???? ??? ?? ???? ?? ??????? ???? ????? ??? ?? ??? ????!!!!      Choose the language                  Select language          ?????          ?????          English            

Each code is in same folder for different language add different value folder

For example value folder for hindi goes inside value-hi

Answer by Virus for Change languages in app via strings.xml


This is a method i wrote and is working perfectly well for me for changing the language from app (and JUST FOR A SINGLE APP - not the entire device):

private void setLanguageForApp(String languageToLoad){      Locale locale;      if(languageToLoad.equals("not-set")){ //use any value for default          locale = Locale.getDefault();      }      else {          locale = new Locale(languageToLoad);      }      Locale.setDefault(locale);      Configuration config = new Configuration();      config.locale = locale;      getBaseContext().getResources().updateConfiguration(config,              getBaseContext().getResources().getDisplayMetrics());  }  

NOTE: Call this method before setContentView() in the first activity's onCreate() everytime when the app is opened.

@Override  protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setLanguageForApp("en"); //hard-coded here - get from whereever you stored      setContentView(R.layout.activity_category_list);      ...      ...      ...  

Store the selected locale code in shared preferences and retrieve to pass as parameter.

Method for language selection dialog: (Note: it reloads app after language change to bring the language change in effect)

private void showLanguageChangePopup() {      CharSequence languages[] = new CharSequence[] {              "English",              "??????????? (Hindi)",              "Fran?ais (French)",              "Italiano (Italian)",              "Deutsch (German)",              "Espa??ol (Spanish)",              "???????? (Japanese)",              "?????? (Korean)",              "Nederlands (Dutch)",              "Portugu??s (Portuguese)",              "??????????? (Russian)",              "???? (Chinese)",              "??????????? (Arabic)"      };      final String codes[] = new String[] {              "en",              "hi",              "fr",              "it",              "de",              "es",              "ja",              "ko",              "nl",              "pt",              "ru",              "zh",              "ar"      };        int currentLangIndex = Prefs.getUserPreferenceIntValue(Prefs.Key.SELECTED_LANGUAGE_INDEX, getBaseContext());      AlertDialog.Builder builder = new AlertDialog.Builder(this);      builder.setTitle(R.string.text_select_language);      builder.setSingleChoiceItems(languages, currentLangIndex, null);      builder.setNegativeButton(R.string.text_translate_cancel, null);      builder.setPositiveButton(R.string.action_change_language, new DialogInterface.OnClickListener() {          public void onClick(DialogInterface dialog, int id) {              int selectedIndex = ((AlertDialog) dialog).getListView().getCheckedItemPosition();              Prefs.setUserPreferenceStringValue(Prefs.Key.LANGUAGE, codes[selectedIndex], getBaseContext());              Prefs.setUserPreferenceIntValue(Prefs.Key.SELECTED_LANGUAGE_INDEX, selectedIndex, getBaseContext());              Intent i = new Intent(CategoryListActivity.this, CategoryListActivity.class);              startActivity(i);              finish();            }      });        builder.show();  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.