我在我的应用程序中将 TableLayout 用作简单的 DataGrid。这些行是在代码中添加的。问题是;当我更改屏幕方向时,新表格布局会出现在旧表格布局上。
布局文件:
.
.
.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView"
android:fillViewport="false"
>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/dataGrid"
android:divider="?android:attr/dividerHorizontal"
android:showDividers="middle|end">
</TableLayout>
</ScrollView>
</TableLayout>
创建测试条目时调用的函数。我从 public View onCreateView
调用它我的 fragment 。
private void fillDataGrid(TableLayout dataGrid,Context context)
{
int columnCount = 5;
int rowCount = 30;
List<TextView> fields = new ArrayList<>();
TableRow row;
dataGrid.removeAllViews();
dataGrid.invalidate();
dataGrid.setStretchAllColumns(true);
for (int j=0;j<rowCount;j++)
{
row = new TableRow(context);
if (j%2 != 0)
row.setBackgroundColor(getResources().
getColor(R.color.highlighted_text_material_light));
for (int i = 0; i < columnCount; i++)
{
TextView field;
field = new TextView(context);
field.setText("field " + i);
fields.add(field);
row.addView(field);
}
dataGrid.addView(row);
}
}
我知道 List<TextView> fields = new ArrayList<>();
的冗余.我保留它以备后用。
SDK 版本:
minSdkVersion 14
targetSdkVersion 22
错误发生在android.app.Fragment
类。
到目前为止我尝试了什么:
- 为我的数据网格 TableLayout、父 TableLayout 和 ScrollView 调用 invalidate() 和 requestLayout() 方法。
- 尝试了解有多少 TableLayout 或 ScrollView 是重复的。根据我的测试代码,结果是无。
- 在 xml 中添加行并忽略 fillDataGrid() 函数并没有解决问题。虽然行是在 xml 中仅添加/操作的。
我学到了什么:
- 这不是渲染问题。因为当我调用
scrollView.setVisibility(View.INVISIBLE);
我仍然可以滚动重复的 TableLayout。
您可以在下面看到描述情况的屏幕截图。
谢谢。
最佳答案
我发现了问题。我在用,
getFragmentManager().beginTransaction()
.add(R.id.mainContainer, fragMain.newInstance("",""))
.commit();
在“onCreate()”方法中将我的第一个 fragment 附加到我的主要 Activity 。由于在方向更改时调用“onCreate()”,因此多次添加了该 fragment 。正确的代码是:
getFragmentManager().beginTransaction()
.replace(R.id.mainContainer, fragMain.newInstance("",""))
.commit();
谢谢。
关于方向改变时 Android TableLayout 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31154971/