我在用代码替换表格行时遇到了一个奇怪的问题。
我的 XML 代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/columnheadings"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="2px"
/>
...
</LinearLayout>
创建 Activity 后,我可以成功地将 TableRow 插入到 TableLayout“columnheadings”:
table = (TableLayout)findViewById(R.id.columnheadings);
table.removeAllViews();
TableRow tr = new TableRow(this);
TextView tv = new TextView(activity);
tv.setText("asdf");
tr.addView(tv);
table.addView(tr);
table.postInvalidate();
表格列的内容(和宽度)是动态计算的。
现在,当 ListView 的适配器内有更新时,我还想重绘 TableLayout。为此,我正在创建引用该 Activity 的适配器。
从适配器内部我可以成功地改变例如列的文本。
我尝试做的(没有成功):
TableLayout tableLayout = (TableLayout)activity.findViewById(android.app.R.id.columnheadings);
tableLayout.removeAllViews();
TableRow row=new TableRow(activity);
TextView tv = new TextView(activity);
tv.setText("test");
row.addView(tv);
tableLayout.addView(row);
tableLayout.postInvalidate();
不幸的是,唯一发生的事情是删除当前表行。新行不会从适配器添加到 tableLayout。
有什么建议吗?
最佳答案
我不记得为什么,但我的代码在所有操作结束时都有 row.getParent().requestLayout();
。好像没有它也不适合我。我的代码中不需要 TableLayout
引用,这就是我使用 row.getParent()
的原因,我认为您可以简单地编写 tableLayout.requestLayout();
它将有所帮助。
关于Android 从代码更改 tableLayout 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3263321/