以编程方式覆盖supportsRtl清单属性

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

有没有办法在运行时在Android中设置/覆盖Manifest中的supports-RTL属性?我希望能够以编程方式切换布局而不实际更改区域设置。从我搜索过的内容来看,我似乎必须为Application和每个活动设置布局方向。有更简单的解决方案吗?

android layout configuration right-to-left
1个回答
0
投票

更新:

this answer,可以使用具有RTL布局方向的语言一次更改所有活动中的布局方向。答案使用Farsi语言进行RTL。如果你想要LTR,你可以使用英语。

在调用onCreate之前,将以下代码放在启动器活动的方法setContentView中:

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

老答案:

您可以在每个活动中获取装饰视图的参考并设置其布局方向。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}

为了缩短这个过程,将上面的代码放在一个公共类onCreateBaseActivity方法中,该方法扩展了AppCompatActivity并使用所有活动作为其子类。

© www.soinside.com 2019 - 2024. All rights reserved.