Android 从代码更改 tableLayout 不起作用

标签 android listview tablelayout

我在用代码替换表格行时遇到了一个奇怪的问题。

我的 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/

相关文章:

android XML TableLayout 问题 : horizontal scroller going outside of right side of screen

安卓用户界面 : New activity or new layout?

android - map 未进入模拟器 android api v2

java - 对于 API >= 26,我应该使用 StartService 还是 StartForegroundService 吗?

android - 如何使用操作栏按钮动态添加到 ListView

android - 将 ListView 中的最后一项放在底部

android - 无法让 TableLayout 中的行水平居中

android - 如何在android中乘以百分比

Android admob 通过 webview 显示横幅广告

android - ImageView 比例类型在列表 Activity 中不起作用