Change navigation bar orientation (RTL) programmatically

萝らか妹 提交于 2019-12-06 10:17:17

问题


My application supports 4 different languages, being two of them written from right to left.

If I change the language from the android system and then start my application, everything works fine. I get a mirrored layout (RTL) and even the navigation bar is mirrored.

My problem is that I have a button in my application to change the language. To change the Locale programmatically I'm doing this:

Locale locale = new Locale("ar")
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

And then recreate the activity:

this.recreate();

The activity is recreated from RTL, but the navigation bar keeps the old style (not mirrored):

Is it possible to mirror the navigation bar programmatically?

EDIT (ADDING IMAGES):

If I change the system language everything work's fine:

If I change the language programmatically, the navigation bar isn't changed:


回答1:


From Android 4.2.2( API Level 17) it supports RTL natively.

When you are changing language pragmatically so how does the OS knows that you want RTL on specific language change. When the language is in RTL format. like when you change locale to Arabic then force system to do RTL and when the app closes then change back to original form.

To force your entire layout to be RTL including the navigation bar orientation (RTL) do the following. Edit your AndroidManifest.xml and add android:supportsRtl="true"

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
...
</application>

to your <application> tag and then add the following line to the top of your Activities' onCreate() method forceRTLIfSupported(); and then insert the follow function into your Activity.

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void forceRTLIfSupported()
{
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){

      //HERE CHECK CONDITION FOR YOUR LANGUAGE if it is AR then
      //change if it is english then don't

      getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);


    }
}

Output:

NOTE:

Specifically "start" means "right" if:

  • the current system language is RTL (Arabic, Hebrew...)
  • AND the android device is API 17 or higher

More info: Android Dev



来源:https://stackoverflow.com/questions/41018281/change-navigation-bar-orientation-rtl-programmatically

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