Search code examples
javaandroidandroid-gridlayout

Creating a simple GridLayout not working


I'm trying to create a simple grid layout in android programatically. It will have a certain number of rows and columns, and just color each square differently. What I have tried seems to color every square the value of the last view (I believe), but I'm not quite sure why. The GridLayout doesn't seem to have very clear documentation. Here's my code:

public static final int GAME_BOARD_COLUMNS = 8;
public static final int GAME_BOARD_ROWS = 8;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_game_board, container, false);
    createGameBoard(view);

    return view;
}

private void createGameBoard(View view) {
    GridLayout grid = (GridLayout)view.findViewById(R.id.grid_layout_game_board);
    grid.setRowCount(GAME_BOARD_ROWS);
    grid.setColumnCount(GAME_BOARD_COLUMNS);

    for (int i = 0; i < GAME_BOARD_ROWS; i++) {
        for (int j = 0; j < GAME_BOARD_COLUMNS; j++) {
            GridLayout.LayoutParams params = 
                new GridLayout.LayoutParams(GridLayout.spec(i), GridLayout.spec(j));

            View square = new View(getActivity());
            int color = Color.rgb(
                    (int) ((255.0f / (float) GAME_BOARD_ROWS) * i),
                    (int) ((255.0f / (float) GAME_BOARD_COLUMNS) * j),
                    100);
            square.setBackgroundColor(color);

            grid.addView(square, params);
        }
    }
}

and the gameboard layout is very simple:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_layout_game_board"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</GridLayout>

When I run this, my screen is simply blue, can't quite figure out why, while debugging the color is different every iteration, so I'm guessing it's not really adding the views to the GridLayout correctly. Anybody had any experience in how to properly populate a GridLayout programmatically?


Solution

  • You might not need to specify LayoutParams. The GridLayout should add cells sequentially as you provide them (using grid.addView(...)).

    Another possible issue is that your square View object. You should make sure that the View object returned has a width and height set and that none of the children in the view (if any) have any widths or heights specified that might fill your screen.