【Android 开发教程】LinearLayout线性布局

本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


LinearLayout把视图组织成一行或一列。子视图能被安排成垂直的或水平的。想知道LinearLayout是如何工作的,首先考虑一下典型的mail.xml文件。

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.   
  12. </LinearLayout>  
在main.xnl中,可以看到,根节点元素是<LinearLayout>,它包含了一个<TextView>元素。这个<LinearLayout>元素控制了它所包含的视图views的顺序。

每一个View和ViewGroup有一些共同的属性,一些例子:

属性描述
layout_width指定View或ViewGroup的宽度
layout_height指定View或ViewGroup的高度
layout_marginTop指定View或ViewGroup上方的额外空间
layout_marginBottom指定View或ViewGroup下方的额外空间
layout_marginLeft指定View或ViewGroup左侧的额外空间
layout_marginRight指定View或ViewGroup右侧的额外空间
layout_gravity指定View或ViewGroup中的子视图的排列位置
layout_weight指定指派给View或ViewGroup的额外空间尺寸
layout_x指定View或ViewGroup的x坐标
layout_y指定View或ViewGroup的y坐标

举个例子,<TextView>元素使用了fill_parent常量,所以的宽度填充了整个它所在布局的宽度。它的高度被设置成wrap_content常量,这意味着,它的高度将和它所在的布局一样。如果不想<TextView>占据整个屏幕,可以把layoutt_width元素设置成wrap_content,就像这样:

[html] view plain copy
  1.     <TextView  
  2.         android:layout_width="wrap_content"  
  3.         android:layout_height="wrap_content"  
  4.         android:text="@string/hello" /><span style="font-family:Arial,Helvetica,sans-serif;">  
  5. </span>  

以上的代码,把TextView的宽度设置成和它所包含的文本的长度一样。

请看如下的布局:

[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="100dp"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.   
  12.     <Button  
  13.         android:layout_width="160dp"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="Button" />  
  16.   
  17. </LinearLayout>  
这里,就把TextView和Button的宽度设置成了一个固定的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值