404response
404response

Reputation: 103

Find a lot of buttons using a for loop (Android Studio)

I have a lot of buttons created and now I want to "get" them using findViewById and a for loop:

public class MainActivity extends AppCompatActivity {

Array buttons[];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    for(int i = 0; i < 10; i++){
        String buttonID = "number" + i;
        int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
        buttons[i] = ((Button) findViewById(resID));
    }
  }
}

But in the line

buttons[i] = ((Buttons) findViewById(resID));

I get this error:

Incompatible types. Required: java.lang.reflect.Array Found: android.widget.button

Upvotes: 0

Views: 348

Answers (2)

Syed Daniyal Nasir
Syed Daniyal Nasir

Reputation: 134

Use the following code.

public class MainActivity extends AppCompatActivity {

Array buttons[];

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

buttons = new Button[10];

for(int i = 0; i < 10; i++){
    String buttonID = "number" + i;
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
    buttons[i] = ((Button) findViewById(resID));
}

} }

Upvotes: 0

chenchuk
chenchuk

Reputation: 5742

Change the

Array buttons[];

To

Button[] buttons = new Button[10];

Upvotes: 2

Related Questions