Android中的RTL Layout

今天,公司的项目完成了,人闲下来了,也开始作了。发现项目的布局文件中好多的warning: Consider replacing android:layout_marginLeft with android:layout_marginStart="30dp" to better support right-to-left layouts
看了警告,急了,什么是right-to-left layouts? 什么是right-to-left layouts?
经过查网查资料,知道了个原由和解决方法,下面简单作个笔记~~


一。RTL Layout由来
平常我们了解的布局习惯都是:从左到右,从上到下。但在很多国家的习惯是:从右到左,从上到下。诸如阿拉伯语、希伯来语等国家就是这种习惯。那对于从右到左的习惯,Android中怎么使用LinearLayout,不好用吧,难道只能用RelativeLayout来实现。这当然不适合Android的初衷和发展。
所以,从Android 4.2开始,Android SDK支持一种从右到左(RTL,Right-to-Left)UI布局的方式,尽管这种布局方式经常被使用在诸如阿拉伯语、希伯来语等环境中,中国用户很少使用。不过在某些特殊用途中还是很方便的。
RTL Layout,就是把界面的右边作为原点,布局方式为:从右到左,从上到下。


二。RTL Layout实现
既然布局方式有从左往右,有从右往左两种。而一般默认布局都为从左往右,那么从右往左的布局如何实现呢?
1)首先要在AndroidManifest.xml文件中将标签的android:supportsRtl属性值设为"true"
2)将相应视图标签的android:layoutDirection属性值设为"rtl"
就是这么简单,其实与我们从左往右的习惯没什么区别,只是要主动标明打开RTL属性而已。
3)不如举个简单例子看看吧
   首先,AndroidManifest.xml文件标签添加一行:
   
android:supportsRtl="true"


   再上布局文件,其中text1/text2为默认LTR布局,而text3/text4才为RTL布局。
   


    

        

        android:layout_marginLeft="30dp"
            android:background="#000000"
            android:gravity="center"
            android:text="text 2"
            android:textColor="#FFFFFF"
            android:textSize="40sp" />
    

    android:layoutDirection="rtl"
        android:orientation="horizontal" >

        

        android:layout_marginRight="30dp"
            android:background="#000000"
            android:gravity="center"
            android:text="text 4"
            android:textColor="#FFFFFF"
            android:textSize="40sp" />
    



   最后看看效果图
   
Android中的RTL Layout_第1张图片

三。marginStart、marginEnd
从上面例子看出,text1/text2为默认LTR线性布局,text2到text1之间的间距用了属性android:layout_marginLeft="30dp";而text3/text4的RTL线性布局中,text4到text3之间的间距用了属性android:layout_marginRight="30dp"
同样是线性布局,同样是第二个控件到第一个控件之间的间距,一个用marginLeft、一个用marginRight,是不是有点乱?是不是不够统一?
Android当然有解决办法,就是引入marginStart、marginEnd这两个属性。
android:layout_marginStart:如果在LTR布局模式下,该属性等同于android:layout_marginLeft。如果在RTL布局模式下,该属性等同于android:layout_marginRight。
android:layout_marginEnd:如果在LTR布局模式下,该属性等同于android:layout_marginRight。如果在RTL布局模式下,该属性等同于android:layout_marginLeft。



四。警告解决方法
既然warning中提到layout_marginStart比layout_marginLeft好,那么把layout_marginLeft换成layout_marginStart不就可以了吗?
直接报错:
To support older versions than API 17 (project specifies 8) you should *also* add android:layout_marginLeft="30dp"
正如上面提到的,RTL Layout是从Android 4.2开始才支持的,之前的版本当然不兼容,那怎么办呢?

解决办法就是layout_marginStart和layout_marginLeft两个属性同时使用,Android会根据版本选择使用。如下:

    

        

                    android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"
            android:background="#000000"
            android:gravity="center"
            android:text="text 2"
            android:textColor="#FFFFFF"
            android:textSize="40sp" />
    



你可能感兴趣的:(Android基础)