Language switching inside app android

后端 未结 2 796
醉酒成梦
醉酒成梦 2020-12-13 22:22

How do I implement language switching without having to manually set locale inside an Android app? I know the app will load the strings.xml according to locale during startu

2条回答
  •  余生分开走
    2020-12-13 22:39

    Ok. Let's do the easy way. In Your Layout folder, do 2 copies of xml layouts. Name one of them main.xml (your local language) and the other one mainen.xml for english. In the values folder, the strings.xml file contains also two lines of text for both of the languages: Tere, Maailm! for local language and Hello World! for english language. Going back to the xml layouts, the main.xml contains android:text="@string/hello" for your text and the second duplicate mainen.xml contains all the same layout and the strings with the slight difference of retrieving the english version of the line of text from the strings.xml file: android:text="@string/hello_en". And programmatically, to set the title when needed and to specify in the beginning of each activity, which layout to choose, use a global variable languageToLoad, that has been declared and instantiated in your first (starting) class: protected static boolean languageToLoad = true;, in that same class the onCreate method should contain some radio buttons (You need to define and name them in corresponding layout xml also): `

        // ...
        View radio1 = findViewById(R.id.Et);
        radio1.setOnClickListener(this);
        View radio2 = findViewById(R.id.En);
        radio2.setOnClickListener(this);
        // ...`
    

    And later in the class:`

        // ...
        public void onClick(View v1) {
                switch (v1.getId()) {
    
                case R.id.Et:
                    languageToLoad = true;
                    break; 
    
                case R.id.En:
                    languageToLoad = false;
                    break;
    
                    // ...`
    

    And later in the program, in the onCreate method of your different activities:`

        //...
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
    
                if (YourSuperClass.languageToLoad) {
                    setContentView(R.layout.youractivity);      // estonian
                    setTitle(R.string.youractivity_title);
                } else {
                    setContentView(R.layout.youractivityen);        // english
                    setTitle(R.string.youractivity_title_en);
                }
    
                Intent i = getIntent();
                //...`
    

提交回复
热议问题