1、相对布局:相对的意思:可以你相对屏幕也可以相对于其他的控件。
布局不仅可以在xml中进行布局,也可以在activity的onCreate方法中进行布局。
2、官方代码:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue" android:padding="10px" >
<!--用来显示Type here的--> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:" /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content"
<!--android:代表访问:android.R文件操作系统的R--> android:background="@android:drawable/editbox_background" android:layout_below="@id/label" /> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/entry"
对齐父元素的右边 android:layout_alignParentRight="true"
控件和控件的间隙 android:layout_marginLeft="10px" android:text="OK" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok" android:layout_alignTop="@id/ok" android:text="Cancel" /> </RelativeLayout>
要求:红色是相对布局,蓝色的现行布局。
代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/number"
android:id="@+id/numberlabel"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/number"
android:layout_toRightOf="@id/numberlabel"
android:layout_alignTop="@id/numberlabel"
android:layout_marginLeft="5dp"
/>
</RelativeLayout>
<!-- 3、请输入短息内容,类型是text,文本值和名都在string.xml中 -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/content"
/>
<!-- 4、第一个文本输入框。为文本输入框,定义一个id,这个id名字是随意起的 -->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="3"
android:id="@+id/content"
/>
<!-- 5、为按钮定义一个id -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>
效果图: