Search code examples
javaandroidandroid-layouttextviewright-to-left

How to apply RTL dynamically and effectively


I'm creating and adding TextViews in linear layout dynamically, whenever I'm applying layoutAmount.setRotationY(180); the layout changes its direction which is right, but the words of TextViews inside it also changes direction which is wrong, for example, if the word is sorry its becomes yrros, how can I apply RTL correctly

Thanks!


Solution

  • setLayoutDirection will set layout direction according to the language

    -Make sure that use layout gravity start and end

     public static void setLanguage(Context context, String language) {
                String[] localeLang = language.split("_");
                Locale locale;
                if (localeLang.length > 1)
                    locale = new Locale(localeLang[0], localeLang[1]);
                else
                    locale = new Locale(localeLang[0]);
                Locale.setDefault(locale);
                Configuration config = new Configuration();
                config.locale = locale;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    config.setLayoutDirection(locale);
                    ((Activity) context).getWindow().getDecorView().setLayoutDirection(config.getLayoutDirection());
                }
                context.getResources().updateConfiguration(config,
                        context.getResources().getDisplayMetrics());
            }