一、线性布局(LinearLayout)
线性布局不会换行,当组件一个一个排列到头时,剩下的组件不会被显示
XML文件控制(一些重要属性)
android:orientation="vertical/horizontal"垂直/水平
android:gravity="center_horizontal"组件中的元素相对于组件的位置
android:layout_gravity="center_horizontal"该组件相对于父容器的位置
android:layout_weight="1"该组件对未占用空间分配权重值,值越大,权重越小
java代码控制
LinearLayout linearlayout=new LinearLayout(this);//创建布局管理器
LinearLayout.setOrientation(LinearLayout.VERTICAL);//设置排列方式
Button button=new Button(this);//创建组件
button.setText("按钮");
button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));//设置按钮长宽
LinearLayout.addView(button);
setContentView(LinearLayout);
二、表格布局(TableLayout)
表格布局布局继承了线性布局,无需声明行列,只需要添加TableRow其他组件来控制表格的行数和列数
一个TableRow就是一个表格行,也是容器,可以不断的向里添加组件,没添加一个子组件该表格就增加一列,列的宽度由该列中最宽的单元格决定
XML文件控制
//跟在TableLayout后面
android:collapseColumns="0"需要被隐藏的列序号,从0开始,用逗号隔开
android:shrinkColumns="3"允许被收缩的列的序号
android:stretchColumns="1"允许被拉伸的列的序号---让最多列的那一行能够布满整行
java代码控制
//创建布局管理器
TableLayout tableLayout=new TableLayout(this);
tableLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
tableLayout.setStretchAllColumns(true);
//创建组件
for(int i=0;i<2;i++){
//创建行
TableRow tableRow=new TableRow(this);
//行中添加数据
for(int j=0;j<=2;j++){
Button button=new Button(this);
button.setText(j+"");
tableRow.addView(button,j);
}
//将组件添加至布局管理器
tableLayout.addView(tableRow);
}
//设置该Activity显示此 布局
setContentView(tableLayout);
三、帧布局(FrameLayout)
帧布局创建一个空白区域,每个组件位于此区域的左上角,每个组件占据一桢,一个一个叠加,帧布局的大小由子控件中最大的子控件决定
XML文件控制
//跟在FrameLayout后面
android:foreground="@drawable/ic_launcher"设置该帧布局容器的前景图像(前景图像:处于帧布局最顶端,不会被覆盖的图片)
android:foregroundGravity="right"前景图像显示的位置
java代码控制
FrameLayout frameLayout=new FrameLayout(this);
//创建两个TextView,设置大小和颜色
TextView textView=new TextView(this);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setHeight(100);
textView.setWidth(100);
textView.setBackgroundColor(Color.BLACK);
TextView textView2=new TextView(this);
textView2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
textView2.setHeight(50);
textView2.setWidth(50);
textView2.setBackgroundColor(Color.RED);
//添加至布局中
frameLayout.addView(textView);
frameLayout.addView(textView2);
//显示布局
setContentView(frameLayout);