我想我对Android布局模型的理解不好,但是我试图创建一个10x10按钮的tableLayout,并且它们一直不显示在屏幕/设备显示之外。
这是我的布局:
<?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>
而且我的代码只是创建行和按钮:
公共类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开发者文档:
列的宽度由该列中具有最宽单元格的行定义。但是,TableLayout可以通过调用setColumnShrinkable()或setColumnStretchable()将某些列指定为可收缩或可拉伸。如果标记为可收缩,则可以缩小列宽以使表格适合其父对象。如果标记为可拉伸,则其宽度可以扩展以适合任何额外的空间。该表的总宽度由其父容器定义]
这可能是原因。您可以使用此方法
setShrinkAllColumns(true)
将所有列标记为可收缩,或使用setColumnShrinkable (int columnIndex, true)
将指示的列标记为可收缩。您也可以像这样android:shrinkColumns="*"
在XML中完成此操作。
有关TableLayout HERE的更多信息。