-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();
}
2
  • 3
    findViewById looks up an item in an existing layout. You should search how to add an item to a layout. Commented Apr 3, 2017 at 17:25
  • 2
    Possible duplicate of Dynamically Creating/Removing Buttons in Android Commented Apr 3, 2017 at 17:31

2 Answers 2

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

int i;
for(i=0; i<10; i++){
    btn[i] = new ImageButton(this);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

oguzhand Thank you very much! This is working, fantastic!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.