动态填充 TableRow 不起作用

Populating TableRow dynamically not working

我在尝试动态填充 TableRow 时遇到了一些问题。我想要做的是,当点击导出按钮时,我编译页眉、页脚和内容,然后在它们完成后,我继续导出为 PDF。

我在 compileContent() 中使用以下代码填充了我的 TableLayout

for (int i = 0; i < allCalibrationList.size(); i++) {
        System.out.println("DATA" + allCalibrationList.get(i).getCalibrationName());
        TableRow row = (TableRow) getLayoutInflater().inflate(R.layout.template_calibration_report_summary_item, summaryTableLayout, false);
        TextView textCol1 = row.findViewById(R.id.row_col1);
        TextView textCol2 = row.findViewById(R.id.row_col2);

        textCol1.setText(allCalibrationList.get(i).getCalibrationName());
        textCol2.setText(getString(R.string.report_not_calibrated_label));
        
        summaryTableLayout.addView(row);
    }
    contentFinished = true;

当我点击导出按钮时:

@Click(R.id.buttonExport)
void buttonExportClicked(View view) {
    FileOutputStream fileOutputStream;
    try {
        while (!headerFinished && !footerFinished && !contentFinished) {
            compileHeader();
            compileContent();
            compileFooter();
        }
        // code to generate pdf
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

问题是,当我第一次单击导出按钮时,它进入了 compileContent() 并且从我放入 for 循环的打印消息中,我设法打印出了数据。但是,tableRow 未显示在导出的 PDF 中。 tableRow 仅在第二次单击导出按钮时才会显示。

但是,当我第二次单击导出按钮时,它并没有进入 compileContent(),因为我在 for 循环中设置的打印消息没有打印出来。为什么会这样?为什么有数据时tableRow不显示?

如果我没理解错的话,你正在做的是更新布局并通过自定义 class 将布局转换为 PDF。更新布局意味着更新 UI,这通常不会立即完成,因为 UI 更新已排队,稍后将在 UI 线程上执行。 (这就是为什么当您的设备繁忙且延迟时,UI 更新速度不够快)

由于 android inflater 的工作原理,您在生成 PDF 时可能无法完成 TableRow 的充气。视图完成膨胀后,您可以使用 View.post() 到 运行 代码。试试这个:

@Click(R.id.buttonExport)
void buttonExportClicked(View view) {
    FileOutputStream fileOutputStream;
    try {
        if (!headerFinished || !footerFinished || !contentFinished) {
            compileHeader();
            compileContent();
            compileFooter();
        }
        summaryTableLayout.post(new Runnable(){
           @Override
           public void run() {
               // code to generate pdf
           }

        })

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}