Android:动态地将图像按钮添加到表布局中的行
我需要向表格布局添加多行,并且需要向每一行添加两个图像按钮。每次启动活动时,行数可能不同 - 我查看 SQLite 数据库,对于数据库中的每一行,我需要添加一个图像按钮。 Table 布局的每一行都会有两个 Image Button。到目前为止,我有这段代码:
db.open();
int count = db.getCount();
boolean newRow = true;
for (int i = 0; i < count; i++) {
if (newRow == true) {
newRow = false;
row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
ImageButton button = new ImageButton(this);
row.addView(button);
tableLayout.addView(row);
}
db.close();
TableRow 行在这段代码上方定义为该活动的变量。我的表布局(代码中的 tableLayout)是在 Activity 布局的 XML 代码中定义的:
<TableLayout
android:id="@+id/tableLayoutContacts"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
行崩溃
代码在tableLayout.addView(row);
,我无法解决此问题。有什么想法吗?谢谢!!
I need to add a number of rows to my Table layout and to each row I need to add two Image Buttons. Number of rows can be different each time I start the Activity - I look into a SQLite database and for each row in the database I need to add an Image Button. And there will be two Image Buttons in each row of Table layout. So far, I have this code:
db.open();
int count = db.getCount();
boolean newRow = true;
for (int i = 0; i < count; i++) {
if (newRow == true) {
newRow = false;
row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
ImageButton button = new ImageButton(this);
row.addView(button);
tableLayout.addView(row);
}
db.close();
TableRow row is defined above this block of code simply as variable for this Activity. My Table layout (tableLayout in code) is defined in XML code of the Activity layout:
<TableLayout
android:id="@+id/tableLayoutContacts"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
The code crashes at the line
tableLayout.addView(row);
I wasnt able to resolve this. Any ideas? Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题是不同的
,您的代码似乎只有一行,并且您一次又一次将该行添加到 tableLayout 中,如下所示。
这将导致在 ViewGroup 的 addViewInner 函数处出现 IllegalStateException
试试这个
I think the problem is different
It seems that Your code will have only one row and you are adding that row again and again to tableLayout as shown below.
This will lead to IllegalStateException at addViewInner Function of ViewGroup
try this