Reputation: 73
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, the Toasts are for testing if what the code is running.
The activity implements OnClickListener
The onClick
method does not work, I used it because I have 42 buttons and I can't write 42 setOnClickListener()
methods for each button.
In the code I create, in two loop, 42 buttons (7*6) and every time each button is pressed it would be disabled and change the background color of the button one time yellow next time red and again.
Upvotes: 3
Views: 163
Reputation:
You must call method in your onCreate()
Try this :
yourbuttonname.setOnClickListener(this);
or
yourbuttonname.setOnClickListener(yourActivity.this);
Upvotes: 0
Reputation: 2814
From the code snipper you've posted, I don't see anything linking the onClick method to your button(s).
Try adding
btn.setOnClickListener(this);
into the for-loop
Upvotes: 4
Reputation: 319
set the onClickListner for your button you have missed that.
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);
btn.setOnClickListener(this);
}
}
Upvotes: 6
Reputation: 68187
You are missing to call the following inside the nested for
loop:
btn.setOnClickListener(this);
Here, this
refers to Activity
which implements OnClickListener
Upvotes: 6