2

I have a Spinner and when I click, for example, to German the App is translated to German. When I restart the App I have the default Language again. My question now is how to save the Language that when I restart the app is still changed in the selected Language?

The code of my Activity is:

private Typeface ttf;

Spinner spinnerctrl;
Button btn;
Locale myLocale;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_einstellungen);
    //Schrift & OnClickListener
    ttf = Typeface.createFromAsset(getAssets(), "schrift.ttf");
    ((TextView)findViewById(R.id.settings_title)).setTypeface(ttf);
    ((TextView)findViewById(R.id.appinfo)).setTypeface(ttf);
    findViewById(R.id.appinfo).setOnClickListener(this);
    ((TextView)findViewById(R.id.settings_back)).setTypeface(ttf);
    findViewById(R.id.settings_back).setOnClickListener(this);
    //Spinner Language
    spinnerctrl = (Spinner) findViewById(R.id.spinner);
    spinnerctrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            if (pos == 1) {
                setLocale("ar");
            } else if (pos == 2) {
                setLocale("en");
            } else if (pos == 3) {
                setLocale("de");
            } else if (pos == 3) {
                setLocale("nv-rUs");
            }
        }
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });
}
//TODO Language translation System
//LanguageTranslation
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, Settings.class);
    startActivity(refresh);
    finish();
}

@Override
public void onBackPressed() {
}

@Override
public void onClick(View view) {
    if(view.getId()==R.id.appinfo) {
       showAppinfo();
    } else if(view.getId()==R.id.settings_back) {
        finish();
    }
}

private void showAppinfo() {
    final Dialog dialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
    dialog.setContentView(R.layout.dialog_appinfo);
    ((TextView)(dialog.findViewById(R.id.appinfo_herrausgeber))).setTypeface(ttf);
    ((TextView)(dialog.findViewById(R.id.appinfo_name))).setTypeface(ttf);
    ((TextView)(dialog.findViewById(R.id.appinfo_version))).setTypeface(ttf);
    ((TextView)(dialog.findViewById(R.id.appinfo_developer))).setTypeface(ttf);
    ((TextView)(dialog.findViewById(R.id.appinfo_back))).setTypeface(ttf);
    dialog.findViewById(R.id.appinfo_back).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
            return;
        }
    });
    dialog.show();
}

}

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    you can save last selected Language i shared preferences and when start your app check what last selected language and init you app with this language – Constantin Cerberus Aug 30 '15 at 13:15
  • possible duplicate of [How to save data in an android app](http://stackoverflow.com/questions/10962344/how-to-save-data-in-an-android-app) – bendaf Aug 30 '15 at 14:14

4 Answers4

1

Ok, it's working, though you have to completely restart the app in order for locale to change. I believe you will be able to figure out how to make it to make changes instantly ; )

public class MainActivity extends AppCompatActivity
{
    SharedPreferences sharedPreferences;

    @Override protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences( getApplicationContext( ) );
        setLocale( sharedPreferences.getString( "user_locale", "en" ) );

        setContentView( R.layout.activity_main );

        Spinner spinner = ( Spinner ) findViewById( R.id.spinner );
        spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener( )
        {
            @Override public void onItemSelected( AdapterView< ? > parent, View view, int position, long id )
            {
                switch( position )
                {
                    case 1:
                        setLocale( "de" );
                        break;

                    case 2:
                        setLocale( "ru" );
                        break;

                    default:
                        setLocale( "en" );
                        break;
                }
            }

            @Override public void onNothingSelected( AdapterView< ? > parent ) { }
        } );
    }

    public void setLocale( String lang )
    {
        Locale myLocale = new Locale( lang );

        if( IsLocaleValid( myLocale ) )
        {
            // Setting default locale to myLocale
            Locale.setDefault( myLocale );

            // Getting required variables
            Resources res = getApplicationContext( ).getResources( );
            Configuration conf = res.getConfiguration( );

            // Setting required info
            conf.locale = myLocale;
            res.updateConfiguration( conf, null );

            SharedPreferences.Editor editor = sharedPreferences.edit( );
            editor.putString( "user_locale", lang ).apply( );
        }

        else
        {
            // Logging so that you know that you have error somewhere ; )
            Log.w( "Locale", "Entered invalid locale: " + lang );
        }
    }

    private boolean IsLocaleValid( Locale locale )
    {
        return Arrays.asList( Locale.getAvailableLocales( ) ).contains( locale );
    }

}

P.S. Sorry that I was so long, I just had some other really important stuff to do : /

P.P.S. Please, let me know if it's working : P

Sw3das
  • 157
  • 1
  • 12
0
SharedPreferences mylanguage;
SharedPreferences.Editor myeditor;
String lang;

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

   mylanguage=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
     lang=mylanguage.getString("mylang","en"); //en is default when user no select

                  myeditor=mylanguage.edit();
               if(lang.equals("ar")) {
               setLocale("ar");


                     } else if(lang.equals("en")) {
                      setLocale("en");
                    } else if(lang.equals("de")) {
                      setLocale("de");
                   } else if(lang.equals("nv-rUs")) {
                      setLocale("nv-rUs");
                                             }
                                                    }


    spinnerctrl = (Spinner) findViewById(R.id.spinner);

        spinnerctrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                                    if (pos == 1) {
                                        setLocale("ar");
                    myeditor.putString("mylang","ar");
                                myeditor.commit();


                                    } else if (pos == 2) {
                                        setLocale("en");
                    myeditor.putString("mylang","en");
                                myeditor.commit();
                                    } else if (pos == 3) {
                                        setLocale("de");
                    myeditor.putString("mylang","de");
                                myeditor.commit();
                                    } else if (pos == 3) {
                                        setLocale("nv-rUs");
 myeditor.putString("mylang","nv-rUs");
                                myeditor.commit();
                                    }
0
  • use SharedPreferences and set default locale flag in SharedPreferences
  • update locale every time user chooses from the spinner and check locale from there every time the app is started.
  • update spinner with saved locale from SharedPreferences.
Poe Poe
  • 76
  • 1
  • 7
0

I implemented a language switch feature a long time ago. It didn't need an app restart to change the locale. To get that to work you have to keep in mind that when applying any configuration update you must ensure that all activities are able to handle that configuration change. Just applying it is not enough. As you know, the default way that Android handles configuration changes is by destroying your activity and recreating it. Another option you have is to indicate in your manifest that you want to handle that configChange.

For the first option, all you need to do is call recreate() on your activity. Well that's almost all you need to do. Android keeps parent activities alive when possible (their onStop() method was called but not their onDestroy()). So those activities will need to be recreated with the new configuration as well. You may already have some idea of how to implement that. I will leave it up to you to find the best way. If you need a hint, look at Application.Activity LifecycleCallbacks.

The default way of handling configuration changes is not very user friendly. Destroying and recreating an activity is notably slow and clunky. Manually handling a locale change results in the best user experience. However, in your situation, since you already destroy your activity after you apply the locale change the user experience will not be that greatly disturbed if you use the recreate method.

After all that's done, you recreated all activities after applying the change, you still lose the new configuration. Well that's what happened to me. If that's also the case for you, you will need to apply the configuration update again in onCreate() and before calling super.onCreate().

Jozua
  • 1,274
  • 10
  • 18