Android : Change entire app layout directions programmatically

孤人 提交于 2019-11-30 02:58:49
Afshin

You can use this piece of code while your application's minSdk >= 17.

I used fa for Farsi, you can use other rtl language.

Configuration configuration = getResources().getConfiguration();
configuration.setLayoutDirection(new Locale("fa"));
getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());

Try code below if you want to change language in the app and change directions in views and resources on active layout:

// set Persian language in the app
setLanguage(context, "fa");

public void setLanguage(Context c, String lang) {
    Locale localeNew = new Locale(lang);
    Locale.setDefault(localeNew);

    Resources res = c.getResources();
    Configuration newConfig = new Configuration(res.getConfiguration());
    newConfig.locale = localeNew;
    newConfig.setLayoutDirection(localeNew);
    res.updateConfiguration(newConfig, res.getDisplayMetrics());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        newConfig.setLocale(localeNew);
        c.createConfigurationContext(newConfig);
    }
}

Also, after changing the language, you need to change the directions for the already created views on the active layout. You can do this with this code:

if (TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL) {
        view.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
} else {
        view.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
}

Change the whole layout

 LinearLayout linrtl=(LinearLayout)findViewById(R.id.linrtl);
 linrtl.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

The back button stays in LTR mode, because it only has one resource, which is an arrow pointing to the left. You need to specify a new resource folder e.g drawable-ldrtl-hdpi and put the same icon which is pointing right in this folder.

SimK

I also have this problem, i find that if your view's width set MATCH_PARENT, you should set the view's gravity with Gravity.LEFT in LTR model and set the view's gravity with Gravity.RIGHT in RTL model.

Sachin Suryavanshi

Following code will work:

    Resources your_resource = context.getResources();

    Configuration config = your_resource.getConfiguration();
    config.locale = locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.setLayoutDirection(locale);
    }

where locale is object of Locale

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