activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- rowCount行数 -->
<!-- columnCount列数 -->
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="6"
android:columnCount="4"
android:id="@+id/root"
>
<!-- layout_columnSpan合并4个横向单元格 -->
<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>
MainActivity.java
package com.example.dk.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.widget.Button;
import android.widget.GridLayout;
public class MainActivity extends AppCompatActivity{
private GridLayout gridLayout;
private 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 = (GridLayout) findViewById(R.id.root);
for (int i = 0; i < chars.length; i++) {
Button btn = new Button(this);
btn.setText(chars[i]);
btn.setTextSize(40);
btn.setPadding(5,35,5,35);
//指定该组件所在的行
GridLayout.Spec rowSpec = GridLayout.spec(i / 4 + 2);
//指定该组件所在的列
GridLayout.Spec columnSpec = GridLayout.spec(i % 4);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
//知道该组件占满父容器
params.setGravity(Gravity.FILL);
gridLayout.addView(btn,params);
Log.d("MainActivity", "i:" + i);
}
}
}