我们正在制作BINGO游戏,其中我们有25个按钮,我创建了他们的对象和一个存储它们的数组。现在我需要在多个函数中访问这些按钮对象。我在哪里准确地声明那些按钮的对象?此外,我在onCreate()之后定义了我班级中的所有函数。我需要访问show(),acceptNum(),client_row()中的那些按钮对象,我应该在哪里以及如何声明它?请帮忙!
public class bingo extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bingo);
}
Button b1 = (Button) findViewById(R.id.button);
Button b2 = (Button) findViewById(R.id.button2);
Button b3 = (Button) findViewById(R.id.button3);
Button b4 = (Button) findViewById(R.id.button4);
Button b5 = (Button) findViewById(R.id.button5);
Button b6 = (Button) findViewById(R.id.button6);
Button b7 = (Button) findViewById(R.id.button7);
Button b8 = (Button) findViewById(R.id.button8);
Button b9 = (Button) findViewById(R.id.button9);
Button b10 = (Button) findViewById(R.id.button10);
Button b11 = (Button) findViewById(R.id.button11);
Button b12 = (Button) findViewById(R.id.button12);
Button b13 = (Button) findViewById(R.id.button13);
Button b14 = (Button) findViewById(R.id.button14);
Button b15 = (Button) findViewById(R.id.button15);
Button b16 = (Button) findViewById(R.id.button17);
Button b17 = (Button) findViewById(R.id.button18);
Button b18 = (Button) findViewById(R.id.button19);
Button b19 = (Button) findViewById(R.id.button20);
Button b20 = (Button) findViewById(R.id.button21);
Button b21 = (Button) findViewById(R.id.button22);
Button b22 = (Button) findViewById(R.id.button23);
Button b23 = (Button) findViewById(R.id.button24);
Button b24 = (Button) findViewById(R.id.button25);
Button b25 = (Button) findViewById(R.id.button26);
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};
public void show()
{...}
public void acceptNum()
{...}
public void client_row()
{...}
}
}//closing class
答案 0 :(得分:1)
你在onCreate之外声明你的按钮并在OnCreate中初始化它:
public class bingo extends AppCompatActivity{
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bingo);
b1 = (Button) findViewById(R.id.button);
}
public void show()
{...}
public void acceptNum()
{...}
public void client_row()
{...}
}//closing class
答案 1 :(得分:0)
也许尝试将它们作为类成员实现:
public class Bingo extends AppCompatActivity {
private Button b1;
// more buttons here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bingo);
b1 = (Button) findViewById(R.id.button);
// other findViewByIds here
}
public void someOtherMethod() {
// do something with the buttons
}
}