[英]displaying numbers in BINGO game on button click in Android
I am making a BINGO game in android, where there are 25 buttons as shown in pic. 我正在用Android制作BINGO游戏,其中有25个按钮,如图所示。 here is the layout Now whenever i will click a button, a number from 1 to 25 to should appear on the clicked button. 这是布局现在,每当我单击一个按钮时,被单击的按钮上应出现一个从1到25的数字。 The problem arises when i want to write a single function, what should i pass as object so that 'the button I clicked -> its object should be invoked -> and only that buttons text should be set as a number.' 当我想编写一个函数时,就会出现问题,我应该将什么作为对象传递,这样“单击的按钮->其对象应该被调用->并且仅将按钮文本设置为数字”。 This is the MainActivity.java file. 这是MainActivity.java文件。
public class MainActivity extends AppCompatActivity {
//made 25 objects for 25 buttons
public static int cnt=0;
//button array
Button butt[]={b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void show(View view)
{
cnt++;
if(cnt<26)
{
b1.setText(cnt); //what should i write here for different
//button objects, so that text for each button
//is set on clicking, without defining 25
//different functions
}
}
}
On every button click, control comes at show(). 每次单击按钮时,控件位于show()处。
The output after clicking all buttons, should have 1 number, from 1 to 25 in each box. 单击所有按钮后,输出应有1个数字,每个框中从1到25。 Please help! 请帮忙!
You can set an OnClickListener foreach button in array: 您可以在数组中设置一个OnClickListener foreach按钮:
public void show(View view)
{
cnt++;
if(cnt<26)
{
for(int i = 0; i<butt.length; i++){
final Button b = butt[i];
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.setText("Some number");
}
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.