如何让 tableLayout 元素适合屏幕

How to make tableLayout elements fit screen

我想我对 Android 的布局模型的理解并不好,但我正在尝试创建一个 10x10 按钮的 tableLayout,但它们总是从 screen/device 显示中消失。

这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TableLayout
        android:id="@+id/table"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10">
    </TableLayout>
<!-- BUTTONS WILL BE HERE-->
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

我的代码只是创建行和按钮:

public class MainActivity 扩展 AppCompatActivity { LinearLayout.LayoutParams 参数 = 新 LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TableLayout tl = findViewById(R.id.table);
    for(int i=0;i<10;i++){
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1));
        for(int j=0;j<10;j++){
            Button b = new Button(this);
            b.setText(" ");
            //b.setLayoutParams(params); //if I uncomment this, the buttons don't show ???
            tr.addView(b);
        }
        tl.addView(tr);
    }
}

}

感谢您的帮助,如果有人能指导我学习如何使用 Android 制作 UI,我将不胜感激。

来自 Android 开发者文档:

The width of a column is defined by the row with the widest cell in that column. However, a TableLayout can specify certain columns as shrinkable or stretchable by calling setColumnShrinkable() or setColumnStretchable(). If marked as shrinkable, the column width can be shrunk to fit the table into its parent object. If marked as stretchable, it can expand in width to fit any extra space. The total width of the table is defined by its parent container

这可能是原因。您可以使用此方法 setShrinkAllColumns(true) 将所有列标记为可收缩或 setColumnShrinkable (int columnIndex, true) 将指示的列标记为可收缩。您也可以在 XML 中这样做 android:shrinkColumns="*".

有关 TableLayout 的更多信息 HERE