androidmultilingualidiomsmultiple-languages

How to change the language of the app when THE USER selects the language?


How to change the language of the app when THE USER selects the language?

I want to do almost this: http://snowpard-android.blogspot.com.br/2013/03/programmatically-change-language-in.html?google_comment_id=z13isbsazkf3hzea504celo5oy3rjzbyevo0k

but instead of changing the language of a textView, I want to create a button with the name of the language, and when the user clicks on it, it goes to a second page already translated. I already created new values with the languages, but can't think about a code that could open another page with those strings. Could anyone help me, plssss?


Solution

  • I would suggest to pass the language name as an intent extra in the first activity and get it in the second activity and update the language accordingly. Consider the following

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // findViewbyId here for button
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, OtherActivity.class);
                    intent.putExtra("lang", "fr");
                    startActivity(intent);
                }
            });
        }
    }
    

    and in the other activity

    public class OtherActivity extends AppCompatActivity {
    
        @Override
        private void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            String lang = getIntent().getStringExtra("lang") == null ? getIntent().getStringExtra("lang") : "en";
    
            // assuming this is the method you have to call to change the language
            changeLang(en);
        } 
    }
    

    Hope this helps.