Search code examples
javaandroidxmlandroid-edittexttextview

Is there any way to automatically set the all layouts to support for both RTL and LTR direction types of languages in android


I am 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.


Solution

  • 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.