在 LTR 设备上强制 RTL

问题描述 投票:0回答:5

标题说明了一切。我找到了几种使用 Facebook 的 I18nManager 将应用程序的默认布局设置为 RTL 的方法,但它仅在第二次应用程序启动时才执行此操作。

代码示例:

I18nManager.forceRTL(true)

我不想让用户能够更改语言,因为应用程序本身是阿拉伯语的。我到处都搜索过,但都在谈论如何支持 RTL,但实际上并没有将其用作默认布局。

有没有办法通过 I18nManager 实现此目的,还是我必须对我的本机代码进行一些更改?

android react-native
5个回答
14
投票

将此行代码添加到所有 Activity 的 onCreate 方法的最顶部(在 super 和 setContentView 之前):

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

并确保清单中的 supportRtl 等于 True。


9
投票

首先,在清单中添加 RTL 支持,如下所示:

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

然后,在您的启动器 Activity 中添加以下代码

onCreate()

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

4
投票

MageNative的答案是正确的。唯一的事情就是设置

locale
,这样的设置已被弃用。您需要使用
setLocale()
方法,如下所示:

Locale locale = new Locale("fa_IR"); // This is for Persian (Iran)
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());

您需要导入

java.util.Locale
android.content.res.Configuration


0
投票

您必须在两个地方执行此操作:

首先: 在 Manifest 的应用程序标签中,添加对 RTL 的支持,如下所示:

<application
    ...
    android:supportsRtl="true"
    ..>
</application>

第二个: 将其添加为活动的

onCreate()
方法的第一行:

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

如果您有基础活动,您可以执行相同的操作,它将应用于其他子活动。


0
投票

2024 + Kotlin

@ataravati 和 @MageNative 的答案都是正确的,但它们是用 Java 编写的 - 而现代 Android 应用程序是用 Kotlin 编写的。因此,请在清单中添加 RTL 支持,然后在您的

MainActivity.kt
中执行:

// import these in the imports block
import android.content.res.Configuration
import java.util.Locale

// and then, inside the class
override fun onCreate(savedInstanceState: Bundle?) {
  // ...[some generated code]

  val locale = Locale("he_IL")
  Locale.setDefault(locale)
  val config = Configuration()
  config.setLocale(locale)
  getApplicationContext().getResources().updateConfiguration(config, 
  getApplicationContext().getResources().getDisplayMetrics());
  
  // this is autogenerated too, needs to be the last row of the function AFAIK
  super.onCreate(null)
}
© www.soinside.com 2019 - 2024. All rights reserved.