OnClick method not working
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
gl = (GridLayout) findViewById(R.id.grid);
array = new Button[7][6];
Button btn;
for(int i=0; i<7; i++)
{
for(int j=0; j<6; j++)
{
btn = new Button(this);
btn.setId(7*i + j + 1);
array[i][j] = btn;
gl.addView(btn);
}
}
turn = 0;
Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v)
{
Toast.makeText(this, "Test1", Toast.LENGTH_SHORT).show();
if(v instanceof Button)
{
Toast.makeText(this, "Test2", Toast.LENGTH_SHORT).show();
int[] d = GetCellByID(v.getId());
Button b = (Button)v;
b.setEnabled(false);
if(turn == 0)
{
b.setBackgroundColor(Color.YELLOW);
turn = 1;
}
else
{
b.setBackgroundColor(Color.RED);
turn = 0;
}
array[d[0]][d[1]] = b;
}
}
This is the code, Toasts are for testing if the code works. Activity implementsOnClickListener
The method onClick
doesn't work, I used it because I have 42 buttons and I cannot write 42 setOnClickListener()
for each button.
In the code I am creating in two loops 42 buttons (7 * 6) and every time each button is clicked it will be disabled and change the background color of the button once to yellow, next time to red and again.
+3
source to share