Search code examples
androidandroid-layoutandroid-tablelayout

How to make tableLayout elements fit screen


I guess my understanding of Android's layout model isn't good but I'm trying to create a tableLayout of 10x10 buttons and they keep getting out of the screen/device display.

Here's my layout :

<?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>

And my code is just creating rows and buttons :

public class MainActivity extends AppCompatActivity { LinearLayout.LayoutParams params = new 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);
    }
}

}

Thanks for your help and if anyone can lead me to a good tutorial on how to make UIs with Android I'd be thankful.


Solution

  • From the Android Developer documentation:

    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

    This could be the reason why. You can use this method setShrinkAllColumns(true) to mark all columns as shrinkable or setColumnShrinkable (int columnIndex, true) to mark the indicated column shrinkable. You can also do it in the XML like this android:shrinkColumns="*".

    More info on TableLayout HERE.