Android 在线性布局中动态添加更多图像按钮

Android 在线性布局中动态添加更多图像按钮,android,android-layout,android-linearlayout,imagebutton,Android,Android Layout,Android Linearlayout,Imagebutton,在我的android项目中,我有一个表视图,我想动态添加一些图像按钮。所以我这样编码 TableLayout table = (TableLayout)findViewById(R.id.tableLayout_1); TableRow rows = new TableRow(this); rows.setBackgroundColor(Color.parseColor("#eaeaea")); rows.setId(4500+id); ImageButton btns=new ImageB

在我的android项目中,我有一个表视图,我想动态添加一些图像按钮。所以我这样编码

TableLayout table = (TableLayout)findViewById(R.id.tableLayout_1);

TableRow rows = new TableRow(this);
rows.setBackgroundColor(Color.parseColor("#eaeaea"));
rows.setId(4500+id);

ImageButton btns=new ImageButton(this);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            params1.leftMargin = 10;
            params1.bottomMargin = 10;

            btns.setBackgroundResource(R.drawable.accept);

            btns.setId(id);

               btns.setOnClickListener(new OnClickListener() {

                   @Override
                   public void onClick(View v) {
                       int id=v.getId();
                       setFlag(id);
                   }
               });


LinearLayout childLayout = new LinearLayout(context);
childLayout.addView(btns);
rows.addView(childLayout);  
table.addView(rows);
工作正常。但是图像按钮的数量可能会有所不同。有时5-10个按钮 此时,所有按钮都显示在一行中。我想根据如图所示的按钮展开linearlayout和tablerow布局

有什么想法吗

我是android新手,请帮忙


提前感谢

尝试使用GridView,对于您正在尝试的操作,建议使用它。下面是如何使用。


如果您在实施方面遇到困难,请在此处回复。

您好,谢谢您的回复。。。你能展示一个动态代码来创建网格视图和添加图像按钮吗?android开发者的链接很简单,你可以从那里复制粘贴来实现网格视图。显示项目列表并希望添加更多项目后,只需调用gridViewAdapter.add(您的项目),然后调用gridViewAdapter.notifydatasetchanged()实际上我需要对齐linearlayout中的一些图像按钮,并需要根据内部按钮增加linearlayout的高度。现在它只显示一行图像按钮。也就是说,如果宽度可以有4个按钮,那么第5个按钮必须小于1,以此类推。。但现在只显示了4个按钮