简体   繁体   中英

Adding onclicklistener to array of buttons

I am making an app that in order to save time, saves buttons in an array, but can't seem to add onClickListener to the buttons on the array.

when I replace the loop that adds the onClickListener by

buttons[0].setOnClickListener;
button[1].setOnClickListener;

the code works fine but when I replace it with this loop shown below

for (int i = 0; i < 91; i++) 
    buttons[i].setOnClickListener(this);

I get this error "Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference" on the line inside the for loop.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main_activity);
    board = (TableLayout) findViewById(R.id.tableLayout);
    bar = (TableLayout) findViewById(R.id.tableLayout2);
    buttons = new Button[91];
    for (int i = 2; i < 93; i++) {
        String str = "button" + i;
        if (i != 6) {
            button = findViewById(getResources().getIdentifier(str, "id", getPackageName()));
            buttons[i - 2] = button;
        }
    }
    text = findViewById(R.id.textView2);
    for (int i = 0; i < 91; i++) {
        buttons[i].setOnClickListener(this);
    }
}

I expected the onClickListener loop to work but whenever I try to load the activity which these buttons are placed in my application crashes

在设置侦听器之前,请确保正在实例化的每个按钮都已正确实例化,您可以设置断点或记录以检查是否所有内容都已正确实例化。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM