网格布局,按照行、列组成一个个网格
界面代码:
<?xml version="1.0" encoding="utf-8"?> <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:rowCount="6" android:columnCount="4" android:id="@+id/root" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" 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" android:text="0" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_columnSpan="4" android:text="清除" /> </GridLayout>
我们用xml添加两个组件,占4列,然后用代码添加其他16个组件
package com.example.gridlayout import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.Gravity import android.widget.Button import android.widget.GridLayout class MainActivity : AppCompatActivity() { private var chars = arrayOf("7","8","9","/", "4","5","6","x", "1","2","3","--", ".","0","=","+") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var gridLayout = findViewById<GridLayout>(R.id.root) for(i in chars.indices) { val bn = Button(this) bn.text = chars[i] //设置按钮字号大小 bn.textSize = 40F //设置按钮空白区域 bn.setPadding(5,35,5,35) //指定按钮所在的行 val rowSpec = GridLayout.spec(i/4+2) //指定所在的列 val columnSpec = GridLayout.spec(i%4) val params = GridLayout.LayoutParams(rowSpec,columnSpec) //指定组件占满父容器 params.setGravity(Gravity.FILL) gridLayout.addView(bn,params) } } }