[英]onClick method doesnt work
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. 这是代码,Toasts用于测试代码是否正在运行。 The activity implements
OnClickListener
该活动实现
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. onClick
方法不起作用,我使用它因为我有42个按钮,我不能为每个按钮编写42个setOnClickListener()
方法。
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. 在我创建的代码中,在两个循环中,42个按钮(7 * 6),每次按下每个按钮,它将被禁用,并且下次红色再次改变按钮的背景颜色一次黄色。
You are missing to call the following inside the nested for
loop: 您缺少在嵌套
for
循环中调用以下内容:
btn.setOnClickListener(this);
Here, this
refers to Activity
which implements OnClickListener
这里,
this
是指实现OnClickListener
Activity
set the onClickListner for your button you have missed that. 为您错过的按钮设置onClickListner。
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);
}
}
From the code snipper you've posted, I don't see anything linking the onClick method to your button(s). 从你发布的代码片段开始,我没有看到任何将onClick方法与你的按钮相关联的内容。
Try adding 尝试添加
btn.setOnClickListener(this);
into the for-loop 进入for循环
onCreate()中的调用方法
yourButton.setOnClickListener(this);
You must call method in your onCreate() 你必须在你的onCreate()中调用方法
Try this : 尝试这个 :
yourbuttonname.setOnClickListener(this);
or 要么
yourbuttonname.setOnClickListener(yourActivity.this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.