gpt4 book ai didi

android - xml中TableLayout动态添加TableRow

转载 作者:太空狗 更新时间:2023-10-29 13:53:30 24 4
gpt4 key购买 nike

虽然这看起来重复了很多问题,但对我来说还是第一次。我到处搜索,找不到结果,最后张贴在这里。

我正在动态创建一个表,其中 TableLayout 部分是用 xml 部分编写的。

<RelativeLayout
android:layout_width="70dp"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark"
android:id="@+id/componentA">
<TableLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:id="@+id/tl_componentA">


</TableLayout>

</RelativeLayout>

我为表格创建了一个对象

TableLayout tableLayoutA;
tableLayoutA= (TableLayout)view.findViewById(R.id.tl_componentA);

现在我尝试从这里开始动态添加一行

createTableRowColumn(tableLayoutA);

相关函数是

private void createTableRowColumn(TableLayout tableLayout){

TableRow tableRow1= new TableRow(this.context);
tableRow1.setBackgroundColor(getResources().getColor(R.color.colorAccent));
setTableRowColumnProperty(tableRow1);
tableLayout.addView(tableRow1);
}

private void setTableRowColumnProperty(TableRow tableRow){

    TableRow.LayoutParams layoutParams= new TableRow.LayoutParams(70, 40);
tableRow.setLayoutParams(layoutParams);
}

我做了所有这些,但在模拟器中没有任何显示。但是,当我手动在 xml 中提供相同的结构时,一切正常。

出于这个原因,我尝试了一些事情来弄清楚

Toast.makeText(getContext(), tableLayoutA.getHeight()+"", Toast.LENGTH_LONG).show();

总而言之,它显示为 0。我不明白为什么,尽管我已经在 xml 本身中修复了 tableLayoutA 的大小。

最佳答案

现实生活中的表格至少需要一行和一列。您没有看到表格,因为您只创建了一行,但是没有列。

您需要在行中添加一列才能显示某些内容。

试试这个:

  TextView label_date = new TextView(this);
label_date.setText("DATE");
label_date.setTextColor(Color.WHITE);
label_date.setPadding(5, 5, 5, 5);
tableRow.addView(label_date);// add the column to the table row here

tableLayout.addView(tableRow, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

您可以将 textView 替换为您想要的任何值。

tableLayout.addView(tableRow, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

这里发生的事情是,你说,在 tableLayout 中添加一个 View ,你告诉它是哪个 View ,你还说 View 的宽度和高度应该包裹它的内容。

此外,指定 40,70 不是一个好主意,当您有不同的屏幕尺寸时会发生什么。此外,使用库来处理动态 View 的添加和删除。您无需重新发明轮子并节省大量时间和精力。对于表格 View ,https://github.com/EsotericSoftware/tablelayout可能是一个好(不确定)。另一个问题是, TableView 是您要找的吗?确保您没有将 recyclerView 误认为是 TableView ,我这样说是因为我不了解您的用例。

有用的链接:https://technotzz.wordpress.com/2011/11/04/android-dynamically-add-rows-to-table-layout/

关于android - xml中TableLayout动态添加TableRow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42655203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com