Android RTL layout direction align center issue
我正在开发需要支持阿拉伯语的Android应用。 (应该从右到左阅读)。快速搜索解决方案后,我发现android完全支持API级别17中的本机阿拉伯语言,并声明了
android:supportsRtl="true"
在AndroidManifest内的application标签中,这样我就可以使用布局镜像自动翻转布局,以获得更好的从右到左的阅读体验。但是,我注意到在布局镜像期间,在子RelativeLayout内部的视图中使用centerInParent时发生了问题。以下是我的代码和预期的布局。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <RelativeLayout android:background="@color/white" android:layout_height="match_parent" android:layout_width="match_parent" android:padding="20dp"> <RelativeLayout android:background="@drawable/shape_flag_imageview_boarder" android:id="@+id/imageLayout" android:layout_height="wrap_content" android:layout_width="wrap_content"> <ImageView android:id="@+id/image" android:layout_height="100dp" android:layout_width="100dp" android:visibility="invisible" /> <ProgressBar android:id="@+id/progressbar" android:layout_centerInParent="true" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </RelativeLayout> <TextView android:id="@+id/text" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_toEndOf="@id/imageLayout" android:layout_width="wrap_content" android:text="Some text here bla bla bla" android:textColor="@color/black" /> </RelativeLayout> |
上图显示了在正常布局方向上从左到右的预期结果。我将ImageView和ProgressBar一起包装在一个子视图中的原因是,当图像从Internet加载时,我希望ProgressBar显示在ImageView的中间。在我将语言环境更改为阿拉伯语后,它变得像

正如我所尝试并出错的那样,找出这是由ProgressBar的centerInParent引起的。它不是在子视图内部居中,而是使中心与根父视图对齐,后者是最外部的RelativeLayout。以下是从ProgressBar删除centerInParent代码的屏幕快照。
它清楚地表明了布局镜像的效果很好,但是ProgressBar的位置并不是我所期望的。因此,我尝试使用centerVertical和centerHorizo??ntal,结果分别显示在下面的图像中。

这些解决方案均无效,我搜索的主题均与此问题无关。所以我想这可能是Android库中的错误?如果有人知道问题或解决方案,请与我分享。谢谢
我通过将
这是Android框架中的RTL布局错误,仅会特别影响Android 4.2(API 17),并且在AndroidManifest.xml中启用了android:supportsRtl =" true"时也是如此。
当您使用RelativeLayout包含以
您可以像这样用Java代码修复它:
1 2 3 4 5 6 7 8 | View relativeLayout = layoutInflater.inflate(R.layout.my_relative_layout, parent, false); // Fix RTL layout bug on Android 4.2 (for Arabic and Hebrew mode) if (Build.VERSION.SDK_INT == 17 && getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) { // Force a left-to-right layout relativeLayout.setLayoutDirection(View.LAYOUT_DIRECTION_LTR); } |
让我告诉您正确的答案,看一下您的RelativeLayout(id:imageLayout),它的宽度是wrap_content,而您的ProgressBar(id:progressbar)添加一个属性android:layout_centerInParent =" true"。这意味着父级不限制witdh,子级也没有限制要居中,所以父母会被拉长。