0

我需要在随机按钮上执行 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();
            }

    });
4

3 回答 3

1

首先初始化 Button 数组....

buttons[bt1]=new Button(context);
于 2013-11-01T08:33:37.070 回答
1

在这种情况下,在您的活动类中实现 onClickLisnter 接口并void onClick(View v)像这样覆盖 on 方法

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;
    }

}


}
于 2013-11-01T09:01:50.483 回答
0

试试这个

randombutton.setChecked(true);
于 2013-11-01T08:32:57.950 回答