将整个容器划分为rows×columns个网格,每个网格可以放一个组件,也可以设置一个组件横跨多少列,纵跨多少行。
实例:计算器
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="6"
android:columnCount="4"
tools:context=".MainActivity"
android:id="@+id/root">
<!--定义一个横跨四列的文本框,并设置颜色背景等属性-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:layout_columnSpan="4"
android:textSize="50sp"
android:layout_marginLeft="2pt"
android:layout_marginRight="2pt"
android:padding="3pt"
android:layout_gravity="right"
android:background="#eee"
android:textColor="#000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!--定义一个横跨四列的按钮-->
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:text="清除"/>
</GridLayout>
package com.example.gridlayoutactivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Button;
import android.widget.GridLayout;
public class MainActivity extends AppCompatActivity {
GridLayout gridLayout;
//定义16个按钮的文本
String [] chars=new String[]{
"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
".","0","=","+",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout=findViewById(R.id.root);
for(int i=0;i<chars.length;i++){
//创建按钮
Button bn=new Button(this);
bn.setText(chars[i]);
//设置按钮字号大小
bn.setTextSize(40);
//设置按钮四周的空白区域
bn.setPadding(5,35,5,35);
//指定该组件所在的行
GridLayout.Spec rowSpec=GridLayout.spec(i/4+2);
//指定改组件的列
GridLayout.Spec colSpec=GridLayout.spec(i%4);
GridLayout.LayoutParams params=new GridLayout.LayoutParams(rowSpec,colSpec);
//指定该组件占满父容器
params.setGravity(Gravity.FILL);
gridLayout.addView(bn,params);
}
}
}