lmiguelvargasf lmiguelvargasf - 22 days ago 11
Android Question

Android Button with same width and height?

I am making a tic-tac-toe game, and I need to make the width and height of my buttons the same.

This is my xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal" ...>

<TextView
android:textSize="30dp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tic-Tac-Toe" />

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/cell_00"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Button
android:id="@+id/cell_10"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Button
android:id="@+id/cell_20"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

<!--previous linear layout repeats twice more-->

</LinearLayout>


This is my activity:

// imports
import android.view.ViewGroup;
public class TicTacToeActivity extends AppCompatActivity {

private static final int SIZE = 3;

@BindView(R.id.game_feedback)
TextView gameFeedback;

private Button[][] grid = new Button[SIZE][SIZE];
private int[][] cell_ids = {
{R.id.cell_00, R.id.cell_01, R.id.cell_02},
{R.id.cell_10, R.id.cell_11, R.id.cell_12},
{R.id.cell_20, R.id.cell_21, R.id.cell_22}
};

private Button getButtonById(int id) {
return (Button) findViewById(id);
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tic_tac_toe);
ButterKnife.bind(this);
gameFeedback.setVisibility(View.INVISIBLE);
loadGridButtons();

Button button = (Button) findViewById(R.id.cell_00);
int size = button.getLayoutParams().width;
button.setLayoutParams(new ViewGroup.LayoutParams(size, size));
}

private void loadGridButtons() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
grid[i][i] = getButtonById(cell_ids[i][j]);
}
}
}
}


However, I am getting the following error that crashes my app.


FATAL EXCEPTION: main
Process: com.mathsistor.m.tictactoe, PID: 20927
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
cannot be cast to android.widget.LinearLayout$LayoutParams

Answer

Instead of button.setLayoutParams(new ViewGroup.LayoutParams(size, size)); use button.setLayoutParams(new LinearLayout.LayoutParams(size, size));

UPDATE Change (size, size) to (SIZE, SIZE) if that is the variable you are using. Otherwise, replace the variable with whatever size you want.