8.4.6  从右到左布局(RTL Layout)

从Android 4.2开始,Android SDK支持一种从右到左(RTL,Right-to-Left)UI布局的方式,尽管这种布局方式经常被使用在诸如阿拉伯语、希伯来语等环境中,中国用户很少使用。不过在某些特殊用途中还是很方便的。

所谓RTL,就是指按平常习惯在左的视图都会在右侧,在右侧的视图都会在左侧。例如,在线性布局中第1个子视图默认都是在左上角的,如果采用RTL布局,默认就在右上角了。

RTL布局默认是关闭的,如果想使用RTL布局,首先要在AndroidManifest.xml文件中将标签的android:supportsRtl属性值设为"true",然后需要将相应视图标签的android:layoutDirection属性值设为"rtl"。

如果要使用RTL布局,还应该注意一个重要的问题。假设一个水平线性布局中有两个标签:TextView1和TextView2。TextView1位于窗口的左上角,而TextVew2在TextView1的右侧,到TextView1的距离是100dp。实际上就是TextView2的左边缘到TextView1的右边缘的距离。如果当前是默认布局方式(LTR,从左到右,Left-to-Right),只需要将TextView2的android:layout_marginLeft属性值设为"100dp"即可。不过这在RTL布局中却恰好相反。在RTL布局中,TextView1在窗口的右上角,而TextView2却跑到了TextView1的左侧,所以TextView2到TextView1的距离实际上变成了TextView2的右边缘到TextView1的左边缘的距离。因此应该设置TextView2的android:layout_marginRight属性,这样就会造成RTL和LTR两种布局模式中UI排列的混乱。为了解决这个问题,在Android 4.2中新加了如下两个布局属性。

android:layout_marginStart:如果在LTR布局模式下,该属性等同于android:layout_marginLeft。如果在RTL布局模式下,该属性等同于android:layout_marginRight。

android:layout_marginEnd:如果在LTR布局模式下,该属性等同于android:layout_marginRight。如果在RTL布局模式下,该属性等同于android:layout_marginLeft。

首先来看下面的布局。

   
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:background="#000" 
  5.     android:orientation="horizontal" > 
  6.     <TextView 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:background="#F00" 
  10.         android:text="TextView1" 
  11.         android:textSize="30sp" /> 
  12.     <TextView 
  13.         android:layout_width="wrap_content" 
  14.         android:layout_height="wrap_content" 
  15.         android:layout_marginStart="100dp" 
  16.         android:background="#F00" 
  17.         android:text="TextView2" 
  18.         android:textSize="30sp" /> 
  19. LinearLayout> 

该布局是默认的LTR布局,所以两个TextView控件都是从左到右排列的,如图8-16所示。

现在将标签的android:layoutDirection属性值设为"rtl",其他布局代码不动。再运行程序,就会看到如图8-17所示的效果。TextView1和TextView2都是从右侧开始排列的,在不改动其他代码的情况下达到这个效果,全靠TextView2使用了android:layout_marginStart属性设置了两个TextView控件的间距。

更多相关文章

  1. 超级简单的android通过view自带的方法进行裁剪视图,实现圆形,矩形
  2. Android(安卓)用户界面---样式和主题(Styles and Themes)(一)
  3. Android(安卓)listview的适配器以及各种监听、效率的提升
  4. [置顶] android listview 连续调用 getview问题分析及解决。
  5. Android沉浸式状态栏(透明状态栏)最佳实现
  6. Activity的构成
  7. 利用Android属性动画实现Banner的原理与实践
  8. Android(安卓)RecyclerView 的 网格布局 ItemDecoration
  9. Android学习系列(5)--App布局初探之简单模型

随机推荐

  1. 怎样隐藏Android软件盘
  2. java.lang.RuntimeException: setAudioSo
  3. Android(安卓)ANR 分析解决方法
  4. android 操作sdcard中的多媒体文件(一)——
  5. 解决更新并使用最新ADT20不能创建android
  6. [转]Android的Handler总结
  7. Android应用程序的完全退出
  8. 深入浅出 - Android系统移植与平台开发(四
  9. (android)关于ListFragment使用
  10. Android调用ITelephony类的endCall()方法