Search code examples
androidandroid-layoutgrid-layout

Setting button size programatically in grid


Sorry for my title, might not be very explicit. Before I start, just want to let you know I'm really new at Android programming.

So, what I'm trying to create is a sudoku board. It doesn't have to be fancy, I'd rather it be kept simple. This is my onCreate method so far:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);

    for (int col = 0; col < 9; col++) {
        for (int row = 0; row < 9; row++) {
            Button b = new Button(this);
            String text = row + "," + col;
            b.setText(text);
            b.setMinHeight(0);
            b.setMinWidth(0);
            b.setPadding(0,0,0,0);

            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.setMargins(0,0,0,0);
            params.height = LayoutParams.WRAP_CONTENT;
            params.width = LayoutParams.WRAP_CONTENT;
            params.setGravity(Gravity.CENTER);
            params.columnSpec = GridLayout.spec(col);
            params.rowSpec = GridLayout.spec(row);

            b.setLayoutParams(params);
            b.setId(row * 10 + col);
            b.setOnClickListener(this);
            gridLayout.addView(b);
        }
    }
}

I just want to create a 9 by 9 grid of buttons (might change to TextField later). However, I seem to be unable to display all my 9 buttons horizontally without specifically setting the button width. How can I create a square grid of Views that scale with screen size programatically?


Solution

  • Check this article to know how to convert from pixels to dp: Set ImageView Size Programmatically in DP Java

    And change your params.height and params.width to use that method with your desired values. for example:

    dpToPx(25); //size will be 25p