IDEA GridLayout
用xml就直接加就好
详见
https://blog.csdn.net/weixin_39251617/article/details/79711668
但是用Java代码添加就比较麻烦
代码:
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<TextView
android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="just a text view!"
android:background="@android:color/white"
android:textSize="50sp"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"/>
<GridLayout
android:id="@+id/g1"
android:columnCount="4"
android:rowCount="5"
android:layout_below="@+id/t1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/t2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="grid_text"
android:background="@android:color/holo_green_light"
android:textSize="50sp"
android:layout_columnSpan="4"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"/>
</GridLayout>
</RelativeLayout>
Java代码:
package com.example.ruchu.gridlayout;
import android.support.v7.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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = findViewById(R.id.g1);
for (int i = 0; i < 4 ; i++) {
for (int j = 0; j <4 ; j++) {
Button bn = new Button(this);
bn.setText("lll");
bn.setTextSize(40);
bn.setBackgroundColor(0);
bn.setPadding(bn.getLeft(),bn.getTop(),bn.getRight(),bn.getBottom());
GridLayout.Spec rowSpec;
rowSpec = GridLayout.spec(i+1);
GridLayout.Spec columnSpec;
columnSpec = GridLayout.spec(j);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec,columnSpec);
params.setGravity(Gravity.FILL);
gridLayout.addView(bn,params);
}
}
}
}
效果图:
其中注意GridLayout的声明成MainActivity的成员,不能在成员函数内声明(我在这检查了半天),还有xml中第二个TextView的android:layout_columnSpan=”4”不能省略,不然下面的“LLL”就只有一列。