Array of Buttons in Android

后端 未结 6 1908
庸人自扰
庸人自扰 2020-12-29 12:34

I want to map the buttons to an array of buttons and the code has no errors while compiling but there is force close when i run it:

Button buttons[];

@Overr         


        
6条回答
  •  情书的邮戳
    2020-12-29 13:09

    EXAMPLE USAGE:

    Button[] buttons = initializeButtons(3);
    buttons[1].setText("I am button1");
    buttons[2].setText("I am button2");
    buttons[3].setText("I am button3");
    

    FUNCTION:

    public Button[] initializeButtons(int x) {
        Resources res = getResources();
        Button[] buttons = new Button[x];
        for (int i = 0; i < x; i++) {
            String b = "button" + i;
            buttons[i] = (Button) findViewById(res.getIdentifier(b, "id", getPackageName()));
        } return buttons;//to prevent array out of bounds exception start from 0
    }
    

    NOTE: Make sure in your layout the button id is button1, button2, button3, .. .. etc'

提交回复
热议问题