-1

I'm kinda new to programming, I was tring as exercise to create new buttons with a loop, but I cannot figure it out. I've tried:

int i;
    for(i=0; i<10; i++){
        ImageButton btn[i]= (ImageButton) findViewById(R.id.btn);
    }

II pretty sure this is a stupid question, but I could not find the answer.

Summing up my goal would be to do something like this:

loop{
    create_new_button();
}
kefete
  • 33
  • 2
  • 9
  • 3
    findViewById looks up an item in an existing layout. You should search how to add an item to a layout. – RvdK Apr 03 '17 at 17:25
  • 2
    Possible duplicate of [Dynamically Creating/Removing Buttons in Android](http://stackoverflow.com/questions/29741097/dynamically-creating-removing-buttons-in-android) – RvdK Apr 03 '17 at 17:31

2 Answers2

2
ImageButton btn[] = new ImageButton[10];

int i;
for(i=0; i<10; i++){
    btn[i] = new ImageButton(this);
}
krsnk
  • 267
  • 1
  • 10
  • I tried, but this is printing out an error Error:(34, 33) error: ']' expected Error:(34, 34) error: illegal start of expression Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > Compilation failed; see the compiler error output for details. – kefete Apr 03 '17 at 17:33
0

Try this:

First put a linear layout or whatever you want to your xml.

LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);

Then, create an arraylist of ImageButton. In a for loop, initialize your bottons and add to your linear layout.

ArrayList<ImageButton> buttons = new ArrayList<>;

for(int i = 0; i < 10; i++){
    ImageButton button = new ImageButton(context)
    buttons.add(button);
    //optional: add your buttons to any layout if you want to see them in your screen
    layout.addView(button);
}
Oğuzhan Döngül
  • 7,856
  • 4
  • 38
  • 52