一、线性布局权重问题以及布局的嵌套
1.MainActivity.java文件
package com.oldtogether.linearlayoutdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layou.main);
}
}
2.main.xml文件
<?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:orientation="vertical">
<!--头布局-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#f0f"></LinearLayout>
<!--中间布局,在设置时添加背景色的技巧,有利于设计-->
<!--相对最外层的布局而言,设置纵向为0,然后让其独享-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#ff0"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_weight="1"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="按钮1"
android:layout_weight="2"
style="@android:style/Widget.Button" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="按钮2"
android:layout_weight="1"
style="@android:style/Widget.Button" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="按钮3"
android:layout_weight="1"
style="@android:style/Widget.Button" />
</LinearLayout>
<!--脚布局-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#0ff"></LinearLayout>
</LinearLayout>
3.运行结果如下图
二、用相对布局来实现上述布局界面
1.MainActivity.java文件
package com.oldtogether.linearlayoutdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layou.main1);
}
}
2.main1.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--头部-->
<RelativeLayout
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#00f">
</RelativeLayout>
<!--底部-->
<RelativeLayout
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#f0f"
android:layout_alignParentBottom="true">
</RelativeLayout>
<!--中间部分,先设置头部和底部然后再卡中间部分,在设置id是不容易出错-->
<RelativeLayout
android:id="@+id/center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0"
android:layout_below="@id/top"
android:layout_above="@id/bottom">
</RelativeLayout>
</RelativeLayout>
3.布局结果
三、心得总结
1.在布局设计时,一般设置先设置大题框架,将头部、中间部分、底部布满整个界面,并设置背景颜色,加以区分,设计好便可删除相关颜色代码。
2.在UI设计布局设计时,将LinearLayout和RelativeLayout等其他布局相互嵌套,便可更方便的实现更加复杂的布局。