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

[亡魂溺海] 提交于 2019-12-05 22:35:40

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

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!