Is there any way to automatically set the all layo

2019-05-20 02:54发布

问题:

I am new in android development, stuck to change the language of the whole android application. i found a way to set the strings into strings-languagecode in values directory and android:supportsRtl="true" in manifest file, it is good for changing the value of the text fields and their direction LTR and RTL automatically but I am getting the problem in EditText field because it's direction needs to be changed and set by the Java code for every xml file. Is there any way to set the direction of the EditText automatically in whole application with minimum effort? Please note I have minimum api level 15 in my project. Please help me out.

Thanks in advance.

回答1:

You can try these methods to change RTL or LTR layout directions.

For RIGHT TO LEFT:

ex. locale : Arabic(ar), Hebrew(he);

private void setRtl(){
    String languageToLoad  = "ar"; // rtl language Arabic
    Locale locale = new Locale(languageToLoad);  
    Locale.setDefault(locale); 

    Configuration config = new Configuration(); 
    config.locale = locale; 
    getBaseContext().getResources().updateConfiguration(config,  
            getBaseContext().getResources().getDisplayMetrics());
            //layout direction 
    Bidi b = new Bidi(languageToLoad,Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
            b.isRightToLeft();
    //save current locale in SharedPreferences
    SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
    SharedPreferences.Editor editor = languagepref.edit();
    editor.putString("languageToLoad",languageToLoad );
    editor.commit(); 

    startActivity(...);// refresh activity.
}

For LEFT TO RIGHT:

ex locale : English(en), Tamil(ta)., etc.

private void setLtr(){
   String languageToLoad  = "en"; // ltr language English
   Locale locale = new Locale(languageToLoad);  
   Locale.setDefault(locale); 

   Configuration config = new Configuration(); 
   config.locale = locale; 
   getBaseContext().getResources().updateConfiguration(config,  
        getBaseContext().getResources().getDisplayMetrics());
        //layout direction 
   Bidi b = new Bidi(languageToLoad, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
            b.isLeftToRight();
   //save current locale in SharedPreferences
   SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
   SharedPreferences.Editor editor = languagepref.edit();
   editor.putString("languageToLoad",languageToLoad );
   editor.commit(); 

   startActivity(...);// refresh activity.

}

Call these method to change RTL or LTR layout directions.

Happy coding....



回答2:

Absolutely! You can add it to your theme in styles.xml and it will apply to all TextViews:

<item name="android:textDirection">locale</item>

Hope that helps!