LinearLayout注意事项
使用Layout_gravity的一个很重要的问题!!! 问题内容: 在一个LinearLayout的水平方向中布置两个TextView,想让一个左,一个右,怎么搞? 或许你会脱口而出:"gravity设置一个left,一个right就可以啦!" 真的这么简单?你试过吗?写个简单的Layout你就会发现,事与愿违了: 代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.jay.example.getscreendemo.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_gravity="left"
android:background="#FF7878"
android:gravity="center"
android:text="O(∩_∩)O哈哈~" />
<TextView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_gravity="right"
android:background="#FF7428"
android:gravity="center"
android:text="(*^__^*) 嘻嘻……" />
</LinearLayout>
运行结果图:
看到这里你会说:哎呀,真的不行耶,要不在外层LinearLayout加个gravity=left的属性,然后设置第二个 TextView的layout_gravity为right,恩,好我们试一下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="left"
tools:context="com.jay.example.getscreendemo.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:background="#FF7878"
android:gravity="center"
android:text="O(∩_∩)O哈哈~" />
<TextView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_gravity="right"
android:background="#FF7428"
android:gravity="center"
android:text="(*^__^*) 嘻嘻……" />
</LinearLayout>
结果还是一样:
好吧,没辙了,怎么办好?
当 android:orientation="vertical" 时, 只有水平方向的设置才起作用,垂直方向的设置不起作用。 即:left,right,center_horizontal 是生效的。 当 android:orientation="horizontal" 时, 只有垂直方向的设置才起作用,水平方向的设置不起作用。 即:top,bottom,center_vertical 是生效的。
然而,这方法好像并没有什么卵用。比如: 如果只能竖直方向设置左右对齐的话,就会出现下面的效果:
这显然不是我们要的结果把! 综上,要么按照上述给出的规则来布局,不过对于这种情况还是使用相对布局RelativeLayout把! 网上没给出具体的原因,都是说这样改有人说这个和orientation的优先级有关 ,暂且先mark下来吧,后续如果知道原因的话再解释!前面屏幕适配也说过了,布局还是建议使用 RelativeLayout!
学员评价