【问题标题】:ANdroid: Dynamicly add Image Buttons to rows in Table Layout安卓:动态地将图像按钮添加到表格布局中的行
【发布时间】:2012-03-10 14:19:02
【问题描述】:

我需要在我的表格布局中添加一些行,并且我需要在每一行中添加两个图像按钮。每次启动 Activity 时,行数都可能不同 - 我查看 SQLite 数据库,对于数据库中的每一行,我需要添加一个图像按钮。并且表格布局的每一行都会有两个图像按钮。到目前为止,我有这个代码:

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 行在此代码块上方定义为此 Activity 的变量。我的表格布局(代码中的tableLayout)是在Activity布局的XML代码中定义的:

<TableLayout
    android:id="@+id/tableLayoutContacts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >


</TableLayout> 

代码在该行崩溃

tableLayout.addView(row);

我无法解决这个问题。有任何想法吗?谢谢!!

【问题讨论】:

  • 如何在 Java 代码中分配 TableLayout?
  • tableLayout = (TableLayout) findViewById(R.id.tableLayoutContacts);
  • 嗯,我的 LogCat 中有大约 30 个错误(红线)。它以蓝线“关闭虚拟机”开始,而不是橙色“threadid=1:线程退出但未捕获异常(组=0x40015560)”,然后以红线开头 FATAL EXCEPTION: main

标签: android row tablelayout


【解决方案1】:

我认为问题不同

您的代码似乎只有一行,并且您正在将该行一次又一次地添加到 tableLayout 中,如下所示。

tableLayout.addView(row);

这会导致ViewGroup的addViewInner函数出现IllegalStateException

试试这个

db.open();
    int count = db.getCount();
    boolean newRow = false;
    for (int i = 0; i < count; i++) {
        if (i % 2 == 0)
            newRow = true;
        if (newRow == true) {
            newRow = false;
            row = new TableRow(this);
            row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,     LayoutParams.WRAP_CONTENT));
            tableLayout.addView(row);
        }
        ImageButton button = new ImageButton(this);
        row.addView(button);

    }
    db.close();

【讨论】:

  • 哇,我完全没看到...但是现在可以了,非常感谢! :) 但似乎还有另一个小问题......我假设添加一个新行会将其添加到前一行的下方。但是我现在将所有按钮都放在一行中(至少在光学上)......有什么提示吗?谢谢! :)
  • 尝试连续两个按钮的编辑答案
猜你喜欢
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多