Layouts - LinearLayout

来源:互联网 发布:土木转金融 知乎 编辑:程序博客网 时间:2024/06/07 02:55

线性布局特点


线性布局会将容器中的组件一个一个排列起来, LinearLayout可以控制组件 横向 或者 纵向 排列, 通过android:orientation属性控制;
不换行属性 : 线性布局中的组件不会自动换行, 如果组件一个一个排列到尽头之后, 剩下的组件就不会显示出来。


线性布局一个重要的属性:Layout Weight

对于权重的理解很重要而且很有用!

To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to “0dp” (for a vertical layout) or the android:layout_width of each view to “0dp” (for a horizontal layout). Then set the android:layout_weight of each view to “1”.


线性布局例子


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/to" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/subject" />
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/message" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@string/send" />
</LinearLayout>



几个tips

安卓中的 layout_gravity 属性和 gravity属性 有啥区别?

LinearLayout有两个非常相似的属性:
android:gravity与android:layout_gravity。

他们的区别在于:

android:gravity 属性是对该view中内容的限定.比如一个button 上面的text. 你可以设置该text 相对于view的靠左,靠右等位置.

android:layout_gravity是用来设置该view相对与父view 的位置.比如一个button 在linearlayout里,你想把该button放在linearlayout里靠左、靠右等位置就可以通过该属性设置.

即android:gravity用于设置View中内容相对于View组件的对齐方式,而android:layout_gravity用于设置View组件相对于Container的对齐方式。

原理跟android:paddingLeft、android:layout_marginLeft有点类似。如果在按钮上同时设置这两个属性。
android:paddingLeft=”30px” 按钮上设置的内容离按钮左边边界30个像素
android:layout_marginLeft=”30px” 整个按钮离左边设置的内容30个像素

更多线性布局属性

LinearLayout.LayoutParams.


0 0