Java 如何使用Android Studio创建循环按钮

Java 如何使用Android Studio创建循环按钮,java,android,button,Java,Android,Button,我对编程有点陌生,我尝试着用循环创建新的按钮,但我无法理解。 我试过: int i; for(i=0; i<10; i++){ ImageButton btn[i]= (ImageButton) findViewById(R.id.btn); } ImageButton btn[]=新建ImageButton[10]; int i; 对于(i=0;i试试这个: 首先在xml中放置一个线性布局或任何您想要的内容 LinearLayout layout = (

我对编程有点陌生,我尝试着用循环创建新的按钮,但我无法理解。 我试过:

int i;
    for(i=0; i<10; i++){
        ImageButton btn[i]= (ImageButton) findViewById(R.id.btn);
    }
ImageButton btn[]=新建ImageButton[10];
int i;
对于(i=0;i试试这个:

首先在xml中放置一个线性布局或任何您想要的内容

LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
然后,创建ImageButton的arraylist。在for循环中,初始化Botton并添加到线性布局中

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);
}
ArrayList按钮=新建ArrayList;
对于(int i=0;i<10;i++){
ImageButton=新建ImageButton(上下文)
按钮。添加(按钮);
//可选:如果希望在屏幕中看到按钮,请将其添加到任何布局中
布局。添加视图(按钮);
}

findViewById在现有版面中查找项目。您应该搜索如何将项目添加到版面中。我尝试过的项目可能重复,但这是打印出错误错误:(34,33)错误:']'预期错误:(34,34)错误:表达式启动非法错误:任务执行失败“:app:compiledBugJavaWithJavaC.”>编译失败;有关详细信息,请参阅编译器错误输出。非常感谢!这很有效,太棒了!
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
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);
}