【问题标题】:What is this Android Snippet doing?这个 Android 代码段在做什么?
【发布时间】:2026-01-16 12:20:03
【问题描述】:

编辑** 除了我的主要问题之外,我自己想出了答案:

            TableLayout tableLayout = new TableLayout(this);

            TableRow row = new TableRow(getApplicationContext());
            row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
            // inner for loop
            for (int j = 1; j <= courseHoleCount; j++) {
                 **TextView tv = new TextView(getApplicationContext());
                tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                        TableRow.LayoutParams.WRAP_CONTENT));**
                tv.setBackgroundResource(R.drawable.cell_shape);
                tv.setTextSize(30);
                tv.setPadding(5, 5, 5, 5);
                tv.setText(String.valueOf(players[i-1].getScore()[j-1]));// (-1) because j = 1 and not 0.
                row.addView(tv);
            }
            tableLayout.addView(row);


            linearLayout.addView(tableLayout);

在上面的代码 sn-p 中,这是做什么的以及 TableRow.Layout 参数被添加到文本视图布局参数中的原因/原因是什么?

tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                    TableRow.LayoutParams.WRAP_CONTENT));

【问题讨论】:

  • 我基本上最终复制并粘贴了代码生成的程序部分并复制了它,但我仍然不知道为什么我不能通过 XML 获得相同的结果。我仍然对带有 ** 的代码行在做什么感到困惑。
  • 你能给屏幕截图吗?只是为了弄清楚你想要实现什么
  • @ntaloventi 我完全重新回答了我现在适用的问题。通过改变我的要求和解决问题,我得到了我需要的所有其他东西。只需要/想知道底部的 sn-p 正在做什么以及最上面的 sn-p 是上下文(或接近它)意味着什么。
  • 请编辑您的标题以描述您问题的技术问题。

标签: java android android-tablelayout tablerow


【解决方案1】:

正在使用TableRow.LayoutParams,因为tvrow 的子代,TableRow。 如果您查看Android API reference,它会说

设置与此视图关联的布局参数。这些向此视图的父级提供参数,指定应如何排列。

LayoutParams构造函数的两个参数用于设置tv的宽高。由于宽度和高度都设置为WRAP_CONTENT,所以tv的大小will be big enough to enclose its content (plus padding)

【讨论】:

    【解决方案2】:

    TextView 的父级是TableRow,因此TextViews 布局参数应该是TableRow.LayoutParams 类型。

    这与指定完全相同:

    <TableRow ...>
        <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content" />
    </TableRow>
    

    如果将TextView 添加到其他ViewGroup,例如LinearLayout,则需要设置LinearLayout.LayoutParams

    【讨论】:

    • 谢谢,xml参考帮了大忙!