我需要在随机按钮上执行performClick()方法。 获取NullPointerException
final Button[] buttons = {bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9};
bt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View p1)
{
// TODO: Implement this method
int rando = (int) (Math.random()*9);
Button randombutton = (buttons[rando]);
randombutton.performClick();
}
});
答案 0 :(得分:1)
首先初始化Button数组....
像
buttons[bt1]=new Button(context);
答案 1 :(得分:1)
在这种情况下,在您的活动类中实现onClickLisnter接口,并覆盖这样的on void onClick(View v)
方法
public class MainActivity extends Activity implements OnClickListener {
Button[] buttons = new Button[9];
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mlayout);
buttons[0] = (Button) findviewbyId(R.id.btn1);
buttons[1] = (Button) findviewbyId(R.id.btn2);
buttons[2] = (Button) findviewbyId(R.id.btn3);
.
.
.
buttons[8] = (Button) findviewbyId(R.id.btn9);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn1:
// Button 1 clicked do somthing here
break;
case R.id.btn2:
// Button 2 clicked do somthing here
break;
.
.
.
case R.id.btn9:
// Button 9 clicked do somthing here
break;
default:
break;
}
}
}
答案 2 :(得分:0)
试试这个
randombutton.setChecked(true);